如何添加样式到.attr('style','width:newWidth');其中newWidth是动态的

时间:2013-08-14 13:12:03

标签: javascript jquery html

我有一个如下代码

var newWidth = Math.floor(width * .75) + 'px';
$(this).find("input:first").attr('style', 'width:newWidth ');

请你纠正我,因为正确的语法应该是直接传递newWidth不起作用我也必须通过样式才能做到这一点

5 个答案:

答案 0 :(得分:5)

使用.css()

$(this).find("input:first").css('width', newWidth);

答案 1 :(得分:1)

您可以使用css方法:

$(this).find("input:first").css('width', <your dynamic value> + 'px');

以下是documentation的链接。

否则,如果您必须使用attr,您应该可以这样做:

$(this).find("input:first").attr('style', 'width:' + <your dynamic value> + 'px');

答案 2 :(得分:0)

如另一个答案中所述,您可以使用.css()

var newWidth = Math.floor(width * .75) + 'px';
$(this).find("input:first").css({
    width: newWidth
});

或者您可以使用.width(),因为您使用的是px单位:

var newWidth = Math.floor(width * .75);
$(this).find("input:first").width(newWidth);

答案 3 :(得分:-2)

你可以试试这个  .css("width","500px")

答案 4 :(得分:-2)

试试这个

$(this).find("input:first").attr('style', 'width:'+newWidth+'px');