帮我优化这段代码 window.onload = function () { function hotChange() { let current_index = 0; let timer = window.setInterval(antoChange, 3000); const button_li = document.getElementById("button").getElementsByTagName("li"); const pic_li = document.getElementById("banner_pic").getAttributeNames("li"); for (var i = 0; i < button_li.length; i++) { button_li[i].onmouseover = function () { if (timer) { clearInterval(timer); } for (var j = 0; j < pic_li.length; j++) { if (button_li[j] == this) { current_index = j; button_li[j].className = "current"; pic_li[j].className = "current"; } else { pic_li.className = "pic"; button_li[j].className = "but"; } } } button_li[i].onmouseover = function () { timer = setInterval(antoChange, 3000); } } function antoChange() { ++current_index; if (current_index == button_li.length) { current_index = 0; } for (var i = 0; i < button_li.length; i++) { if (i == current_index) { button_li[i].className = "current"; pic_li[i].className = "current"; } else { button_li[i].className = "but"; pic_li[i].className = "pic"; } } } } hotChange(); }
时间: 2024-01-22 19:02:01 浏览: 117
[removed]使用指南
可以尝试以下优化:
1. 如果能使用现代的 JavaScript,可以使用 const 和 let 声明变量,而不是使用 var。
2. 获取 DOM 元素时,尽量避免多次获取相同的元素,可以将其存储到一个变量中。
3. 给按钮绑定 mouseover 和 mouseout 事件时,可以使用 mouseenter 和 mouseleave 事件来替代,这样更加准确。
4. 给按钮绑定事件时,可以使用事件委托的方式,减少事件绑定的次数。
下面是代码优化后的示例:
```
window.onload = function() {
const buttonList = document.querySelectorAll('#button li');
const picList = document.querySelectorAll('#banner_pic li');
let currentIndex = 0;
let timer = setInterval(antoChange, 3000);
function hotChange() {
for (let i = 0; i < buttonList.length; i++) {
buttonList[i].addEventListener('mouseenter', function() {
clearInterval(timer);
currentIndex = i;
changePic();
});
buttonList[i].addEventListener('mouseleave', function() {
timer = setInterval(antoChange, 3000);
});
}
}
function antoChange() {
currentIndex = (currentIndex + 1) % buttonList.length;
changePic();
}
function changePic() {
for (let i = 0; i < buttonList.length; i++) {
if (i === currentIndex) {
buttonList[i].className = 'current';
picList[i].className = 'current';
} else {
buttonList[i].className = 'but';
picList[i].className = 'pic';
}
}
}
hotChange();
}
```
阅读全文