【问题标题】:Best way to change background color with JavaScript HTML DOM使用 JavaScript HTML DOM 更改背景颜色的最佳方法
【发布时间】:2015-05-08 04:30:32
【问题描述】:

使用 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>

【问题讨论】:

标签: javascript css


【解决方案1】:

获取元素,然后使用.style 属性和.backgroundColor 属性来更改它:

function foo(){
  document.getElementById("head1").style.backgroundColor = "yellow";
  }
<!DOCTYPE html>
<html>
<head>
<title>Demo page</title>
</head>
<body>

<h1 id="head1" style="background-color:red">This is a heading</h1>
<button onclick="foo()">Click!</button>

</body>
</html>

因此,您的第二个nd 选项是正确的。

【讨论】:

  • 感谢您的回答。
【解决方案2】:

如果您使用 CSS class 而不是 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>

【讨论】:

  • 感谢您的回答。
  • 如果我的答案符合您的要求,那么您可以接受这个答案。这更好,因为我们在这里使用类而不是内联元素。
猜你喜欢
  • 2011-02-27
  • 1970-01-01
  • 2015-06-23
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2013-02-02
  • 2022-11-02
  • 2023-03-28
相关资源
最近更新 更多