使用jQuery更改div类的样式属性

118

我有一个这样的滑动条类,我想要更改style属性style="left: 336px"

<div id="range-cont">
<div class="slider">
<div class="progress" style="width: 350px;"></div>
    <a class="handle" href="#" **style="left: 336px;"**></a>
</div>
<input id="percentage" class="range" type="range" value="14" name="percentage" min="0" max="100">
<p id="percent-label">%</p>
</div>
</div>

我尝试使用$('.handle').css({'style':'left: 300px'}),但它没有生效。不确定我在这里做错了什么。

9个回答

195

尝试使用$('.handle').css('left', '300px');


101

如果你只想设置样式属性,请使用

$('.handle').attr('style','left: 300px');

或者您可以使用jQuery的css方法来设置一个CSS样式属性。

$('.handle').css('left', '300px');

或者与键值相同

$('.handle').css({'left': '300px'});

W3schools更多信息


2
这个回答更加完整和优秀,比被选中的那个更好。 - Nicola Pedretti
$('.handle').prop('style','left: 300px'); 也是有效的。 - Nurkartiko

9
$('.handle').css('left', '300px');

$('.handle').css({
    left : '300px'
});

$('.handle').attr('style', 'left : 300px');

或者使用OrnaJS。

8

尝试使用

$('.handle').css({'left': '300px'});

或者

$('.handle').css('left', '300px');

与其

$('.handle').css({'style':'left: 300px'})

4

$('.handle').css('left','300px') 尝试这样做,先指定标识符再设定值

关于此更多内容请参见:

http://api.jquery.com/css/


2

this helpful for you..

$('.handle').css('left', '300px');

2

样式是一个属性,因此css不能用于它。您可以使用attr

更改:

$('.handle').css({'style':'left: 300px'});

T0:

$('.handle').attr('style','left: 300px');//Use `,` Comma instead of `:` colon

2

您不能同时使用$('#Id').attr('style',' color:red');$('#Id').css('padding-left','20%');
。您只能在单独使用attrcss时才能正常工作。


0
为了有条件地更改类的属性,
var css_val = $(".handle").css('left');
if(css_val == '336px')
{
  $(".handle").css('left','300px');
}

如果给定id如下,
<a id="handle" class="handle" href="#" style="left: 336px;"></a>

这里有一个替代方案:

var css_val = $("#handle").css('left');
if(css_val == '336px')
{
  $("#handle").css('left','300px');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接