使用JavaScript更改元素的背景颜色的最合适且跨浏览器兼容的方法是什么?
<!DOCTYPE html>
<html>
<head>
<title>Demo page</title>
</head>
<body>
<h1 id="head1" style="background-color:red">This is a heading</h1>
<script>
// this one?
document.getElementById("head1").style["background-color"] = "yellow";
// this one?
document.getElementById("head1").style.backgroundColor = "yellow";
//or this one?
document.getElementById("head1").style.background = "yellow";
</script>
</body>
</html>
如果您使用CSSclass
而不是,则有更好的方法style
。
function foo(){
document.getElementById("head1").className = "newclass";
}
h1{background:gold;}
h1.newclass{background:green;}
<h1 id="head1">This is a heading</h1>
<button onclick="foo()">Click!</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句