如何用javascript更改css属性?

时间:2014-09-19 11:20:51

标签: javascript html css

我尝试使用javascript更改div的margin-top css元素,但它无法正常工作。这是我的代码:

document.getElementById("sidescrollbtn").css({'margin-top':'70px'});

有什么想法吗?

小提琴: http://jsfiddle.net/vinicius5581/2y63xnxa/5/

5 个答案:

答案 0 :(得分:3)

在vanilla JS中,只需设置.style.{camelCasedProperty} = 'value';

即可
document.getElementById("sidescrollbtn").style.marginTop = '70px';

您也可以使用您尝试的对象表示法来使用jQuery:

$('#sidescrollbtn').css({ 'margin-top': '70px' });

答案 1 :(得分:2)

你可以通过以下几种方式实现:

// Reference property name
document.getElementById("sidescrollbtn").style.marginTop = '70px';

OR

// Use setAttribute method
document.getElementById("sidescrollbtn").setAttribute("style", "margin-top: 70px");

OR

// Use jquery .css()
$('#sidescrollbtn').css({ 'margin-top': '70px' });

其他信息

答案 2 :(得分:1)

使用 HTML DOM

document.getElementById(id).style.property=new style

<强> 实施例

<script>
document.getElementById("p2").style.color = "blue";
</script>

答案 3 :(得分:1)

你可以使用

给css
document.getElementById("p2").style.color = "blue";

答案 4 :(得分:0)

在您创建的JSFiddle中,如果您使用以下代码行替换有问题的代码行,这将有效。

document.getElementById("sidescrollbtn").style.marginTop = '70px';

您也可以使用jQuery来应用样式,如下所示

$('#sidescrollbtn').css({ 'margin-top': '70px' });