jQuery更改div类的style属性


87

我有一个这样的滑块类,并且我想更改样式属性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'})但是没有用。不知道我在做什么错

Answers:



84

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

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

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

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

或与键值相同

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

有关W3schools的更多信息


2
这是一个比所选择的答案更完整,更好的答案
Nicola Pedretti

$('.handle').prop('style','left: 300px');也在工作
努尔卡蒂科

8

试试看

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

代替

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

@dev现在更新了,请检查它是否可以正常工作,我误删除了括号
Raghuveer 2013年

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

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

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

或使用OrnaJS




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%');

您可以使用一个,也可以使用attr css但两者都只能在单独使用时起作用。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.