【问题标题】:Use variable in jQuery CSS attribute line [closed]在 jQuery CSS 属性行中使用变量 [关闭]
【发布时间】:2013-07-10 05:09:05
【问题描述】:

我试图做的是计算浏览器高度,将该数字减少约 20%,然后将该数字分配给元素的高度。问题是元素位于可滚动的 div 中,因此仅分配 height: 80% 将不起作用,因为我希望浏览器高度而不是父 div 高度。不幸的是,另一个问题是我必须使用!important 语法来强制它。

这是我目前所拥有的:

var browserHeight = jQuery(window).height();
var desiredHeight = browserHeight * 0.8;
jQuery('##myID .myClass').attr('style', 'height: 100px !important');

我只需要弄清楚如何将100px 替换为desiredHeight,而不会丢失!important

如果您能帮助我,我将不胜感激!即使您有不同的(也许更好的)方法。 :)

【问题讨论】:

  • jQuery('#myID .myClass').attr('style', 'height: '+desiredHeight+'px !important');

标签: jquery css styles height attr


【解决方案1】:

您可以将字符串与变量连接起来:

$('#myID .myClass').attr('style', 'height: ' + Math.round(desiredHeight) + 'px !important');

注意:我从选择器中删除了多余的磅符号,这会导致异常。此外,您不需要重要,因为这是一种内联样式,并且会覆盖元素的所有 css 规则。我会将其切换为使用 css 方法:

$('#myID .myClass').css('height', desiredHeight);

【讨论】:

  • 感谢所有回答的人,你们是最快的。 :) 出于某种原因,它没有将其分配给 CSS,但没有错误,也没有跳过代码。我有一些调查要做。 PS。我绝对需要 !important 和双 # 和 jQuery 而不是 $ - 这是一个 cfm 文件。 ;)
  • 啊 cfm,我明白了。我仍然不明白你为什么需要!important,内联将覆盖适用于该元素的所有 css 规则。不知道为什么这对你不起作用。
  • 我需要它,因为我要修改的元素已经有一个我无法删除的内联值。
  • 哦,我明白了 - 你在元素上有一个 height 属性?尝试创建一个 jsfiddle
  • 嘿,谢谢贾斯汀!您的建议工作得很好,问题是我在元素完全加载之前运行代码,所以它没有应用它。万分感谢!另外,想感谢您提到数学回合 - 好主意!
【解决方案2】:
var browserHeight = $(window).height();
var desiredHeight = browserHeight * 0.8;
jQuery('##myID .myClass').attr('style', 'height: '+ desiredHeight +'px !important');

【讨论】:

    【解决方案3】:

    这应该可以工作

    var browserHeight = jQuery(window).height();
    var desiredHeight = browserHeight * 0.8;
    jQuery('##myID .myClass').attr('style', 'height: '+desiredHeight+'px !important');
    

    【讨论】:

      猜你喜欢
      • 2012-08-28
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 2018-08-09
      • 2015-04-18
      相关资源
      最近更新 更多