【问题标题】:jQuery - Cannot dynamically change height of textarea with CSS !importantjQuery - 无法使用 CSS 动态更改文本区域的高度!重要
【发布时间】:2014-06-24 04:04:52
【问题描述】:

我正在尝试更改文本区域的高度。 Zurb 的基金会已经定义了5rem !important 的高度。

现在,当我尝试使用 jQuery 更改我的高度时,它并没有改变。我试过了:

$('textarea').height('500px')
$('textarea').css('height', '500px', 'important);

没有任何效果。任何其他属性的 CSS 都会随着 .css() 而改变。我能做什么?

【问题讨论】:

  • 已经定义的样式5rem !important是内联样式吗?
  • 没有发现问题:jsfiddle.net/U75uW 你能检查一下其他样式定义是否覆盖了你的 jQuery 样式
  • @blunderboy,不,它是在基金会的 css 文件中定义的。
  • .css('height', '500px', '!important'); - 重要中缺少引号
  • @ShaunakD,不,当您使用 jQuery 时,您不需要 !.css(name, value, priority)

标签: javascript jquery


【解决方案1】:

如果5rem !important 设置为内联样式,则它具有最高优先级,然后您不能通过任何 CSS 规则覆盖它。然后您必须更新内联样式。试试这个:

$('textarea').get(0).style.setProperty('height','200px','important');

来自MDN Docs

CSSStyleDeclaration.setProperty()

没有回报。示例:styleObj.setProperty('color', 'red', 'important')

更新:

请阅读Answer: Apply !important CSS style using jQuery 你会在那里找到非常有用的信息..

编码愉快!!

【讨论】:

    【解决方案2】:

    Demo

    您可以使用 css - 但它不支持 Priority 字段。

    以下是正确的语法:

    $('textarea').css('height','500px')
    

    或者如果你需要important,你可以使用内联样式或者类。

    Demo:添加类

    .areaHeight{
        height : 500px !important;
    }
    
    $('textarea').addClass('areaHeight')
    

    还有其他不太可行的选项:cssText

    【讨论】:

      【解决方案3】:
      $('textarea').attr('style', 'height: 500px !important');
      

      【讨论】:

      • 好的,谢谢!但是为什么我不能只使用.css()??
      • 我不喜欢这样做,因为它会覆盖我的整个内联样式。
      【解决方案4】:

      试试这个

      <textarea id="textareaid"> </textarea>
      $('#textareaid').css('height', '500px');
      

      【讨论】:

      • 欢迎来到 SO!!我看到这是一个新的答案。请尝试阅读现有的答案和确切的问题。您的回答没有回答 OP 的问题。
      【解决方案5】:

      尝试使用其中任何一个来设置高度

      Type:  1
       $("textareaid").height("600")
      
      Type:  2
       $("textareaid").css("height","400px")
      

      确保在创建 dom 元素后调用你的脚本

      【讨论】:

        猜你喜欢
        • 2022-06-11
        • 1970-01-01
        • 2016-06-21
        • 1970-01-01
        • 1970-01-01
        • 2014-09-19
        • 2014-09-19
        • 2023-03-15
        • 1970-01-01
        相关资源
        最近更新 更多