所以说我身体里有这个:
<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>
如何做到这一点?
答案 0 :(得分:2)
使用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";
}
}
}
答案 1 :(得分:0)
我建议与Class Selectors合作。
<body onLoad="getElem();">
<h1>Hello world!</h1>
<h2 class="blue">This is my webpage</h2>
<a class="blue">Welcome!</a><br>
<h3>Goodbye</h3>
</body>
然后,您可以通过document.querySelectorAll()
轻松选择所有具有公共类别的元素document.querySelectorAll(".blue")
所有具有蓝色类别的元素(例如)
然后你可以将每个元素的类简单地设置为黑色。
答案 2 :(得分:0)
function getElem(){
var items = document.body.getElementsByTagName("*");
for (var i = items.length; i--;) {
style = window.getComputedStyle(items[i].innerHTML);
color = style.getPropertyValue('color');
if(color =="rgb(0,0,255)"){
items[i].style.color="black";
}
}
}