[英]How to change a css property with javascript?
我正在尝试使用javascript更改div的margin-top
css元素,但它不起作用。 这是我的代码:
document.getElementById("sidescrollbtn").css({'margin-top':'70px'});
有任何想法吗?
在香草JS中,只需设置.style.{camelCasedProperty} = 'value';
document.getElementById("sidescrollbtn").style.marginTop = '70px';
您也可以使用尝试使用的对象表示法在jQuery中进行操作:
$('#sidescrollbtn').css({ 'margin-top': '70px' });
您可以通过以下几种方法进行操作:
// Reference property name
document.getElementById("sidescrollbtn").style.marginTop = '70px';
要么
// Use setAttribute method
document.getElementById("sidescrollbtn").setAttribute("style", "margin-top: 70px");
要么
// Use jquery .css()
$('#sidescrollbtn').css({ 'margin-top': '70px' });
附加信息
使用HTML DOM
document.getElementById(id).style.property=new style
例:
<script>
document.getElementById("p2").style.color = "blue";
</script>
你可以给CSS使用
document.getElementById("p2").style.color = "blue";
在您创建的JSFiddle中,如果用下面的代码行替换有问题的代码行,则可以使用该代码。
document.getElementById("sidescrollbtn").style.marginTop = '70px';
您还可以通过使用jQuery来应用样式,如下所示
$('#sidescrollbtn').css({ 'margin-top': '70px' });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.