所以说我体内有这个:
<body>
<h1>Hello world!</h1>
<h2 style="color: Blue;">This is my webpage</h2>
<a style="color: Blue;" onClick="changeElem();">Welcome!</a><br>
<h3>Goodbye</h3>
</body>
我想创建函数changeElem()
,以便它将蓝色到黑色的内容更改。所以这是我想要在使用此函数后得到的结果:
<h1>Hello world!</h1>
<h2 style="color: Black;">This is my webpage</h2>
<a style="color: Black;" onClick="changeElem();">Welcome!</a><br>
<h3>Goodbye</h3>
如何才能做到这一点?
您最好使用CSS而不是内联样式进行此操作。
<head>
<style>
/* By default, elements with class="some-class" are blue */
.some-class {
color: blue;
}
/* But if body has the class "updated", they turn black */
body.updated .some-class {
color: black;
}
</style>
<h1>Hello world!</h1>
<h2 class="some-class">This is my webpage</h2>
<a class="some-class" onClick="changeElem();">Welcome!</a><br>
<h3>Goodbye</h3>
</body>
...在哪里changeElem
:
function changeElem() {
document.body.className += " updated";
}
如果你死心塌地使用内联样式,这是不是一个好主意,你仍然可以做到这一点很容易不够:
function changeElem() {
var div, colorValue, list, index, element;
// Figure out what this browser returns for `color: Blue`
// (it might be "Blue", "blue", "rgb(0, 0, 255)",
// "rgba(0, 0, 255, 0)", "#0000FF", "#0000ff",
// or possibly others)
div = document.createElement('div');
document.body.appendChild(div);
div.innerHTML = '<span style="color: Blue;"></span>';
colorValue = div.firstChild.style.color;
document.body.removeChild(div);
// Get list of all elements that have any `style` attribute at all
list = document.querySelectorAll('[style]');
// Loop through looking for our target color
for (index = 0; index < list.length; ++index) {
element = list[index];
if (element.style.color === colorValue) {
element.style.color = "black";
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句