在jQuery CSS属性行中使用变量

时间:2013-07-11 19:22:34

标签: jquery css styles height attr

我尝试做的是计算浏览器高度,将该数字减少大约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

如果你能帮助我,我一定很感激!即使你有一个不同的(可能更好的)方法。 :)

3 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

这应该有效

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