我是JS的新手并且正在进行需要的类分配:
当用户点击突出显示按钮时,将css类应用于每个其他li元素,以便交替显示颜色,并显示图像。
我无法让颜色更改的切换工作,我也无法显示图像。
<script>
var colors = new Array()
colors[0] = "#cc0099";
colors[1] = "#a4c400";
colors[2] = "#9900cc";
var counter = 0;
window.onload = function()
{
var highlightBtn= document.getElementById("highlight_btn");
highlightBtn.onclick = switchColors;
}
function switchColors()
{
var imgSrc = "images/" + [i];
var changeLI = document.getElementsByClassName("change");
changeLI.innerHTML = counter;
counter++;
}
</script>
<h1>Happy Mothers Day!</h1>
<h2>Things to get Mom:</h2>
<ul>
<li class="change">New Plants</li>
<li>Flowers</li>
<li class="change">A Day at the Spa</li>
<li>A Picture of Yourself</li>
<li class="change">New Shoes!</li>
<li>Anything with a Heart on It</li>
<li class="change"> Chocolate</li>
</ul>
<input id="highlight_btn" type="button" value="Highlight">
答案 0 :(得分:0)
使用getElementsByClassName而不是getClass,它甚至没有在文档中定义。要更改颜色,请使用Element.style.color属性。
var changeLi = document.getElementsByClassName("change");
for(var i = 0; i < changeLi.length; i ++) {
changeLi[i].style.color = colors[i];
});
答案 1 :(得分:0)
你可以做这样的事情(它不清楚你想要什么),但这显示了你的原则。
HTML
<h1>Happy Mothers Day!</h1>
<h2>Things to get Mom:</h2>
<img id="mom" src="">
<ul>
<li class="change">New Plants</li>
<li>Flowers</li>
<li class="change">A Day at the Spa</li>
<li>A Picture of Yourself</li>
<li class="change">New Shoes!</li>
<li>Anything with a Heart on It</li>
<li class="change">Chocolate</li>
</ul>
<input id="highlight_btn" type="button" value="Highlight">
的Javascript
var colors = [];
var images = [];
var counter1 = 0;
var counter2 = 0;
colors.push("#cc0099");
colors.push("#a4c400");
colors.push("#9900cc");
images.push("http://imageshack.us/scaled/thumb/104/9071003006mini2lpl0.jpg");
images.push("http://imageshack.us/scaled/thumb/121/spirra.jpg");
images.push("http://imageshack.us/scaled/thumb/123/s4020001ret9qr.jpg");
function switchColors() {
var changes = document.getElementsByClassName("change");
Array.prototype.forEach.call(changes, function (change) {
change.style.backgroundColor = colors[counter1];
});
counter1 += 1;
if (counter1 > colors.length - 1) {
counter1 = 0;
}
document.getElementById("mom").src = images[counter2];
counter2 += 1;
if (counter2 > images.length - 1) {
counter2 = 0;
}
}
window.addEventListener("load", function () {
document.getElementById("highlight_btn").addEventListener("click", switchColors, false);
}, false);
on jsfiddle