window.onload = function () { function hotChange() { var current_index = 0; var timer = window.setInterval(antoChange, 3000); var button_li = document.getElementById("button").getElementsByTagName("li"); var 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-16 22:01:50 浏览: 62
【JavaScript源代码】用JavaScript实现轮播图效果.docx
这段代码存在一些问题,我为您提供以下优化建议:
1. 在获取 banner_pic 元素的属性名时,应该使用 getElementsByClassName 方法而不是 getAttributeNames 方法。
2. 在 for 循环中,应该使用 let 关键字或是闭包来避免变量作用域污染。
3. 在自动轮播的函数中,应该使用比较运算符 "==" 而不是赋值运算符 "=" 进行判断。
4. 在鼠标悬停时,应该使用 setTimeout 和 clearTimeout 方法来实现暂停和继续轮播的效果。
5. 应该将获取元素的代码封装为函数,以便于代码重用和维护。
根据以上建议,重构后的代码如下:
```
window.onload = function () {
function hotChange() {
let current_index = 0;
let timer = setInterval(antoChange, 3000);
const button_li = getElements(".button li");
const pic_li = getElements(".banner_pic li");
for (let i = 0; i < button_li.length; i++) {
button_li[i].onmouseover = function () {
clearInterval(timer);
for (let 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 {
button_li[j].className = "but";
pic_li[j].className = "pic";
}
}
}
button_li[i].onmouseout = function () {
timer = setInterval(antoChange, 3000);
}
}
function antoChange() {
++current_index;
if (current_index == button_li.length) {
current_index = 0;
}
for (let 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";
}
}
}
function getElements(selector) {
return document.querySelectorAll(selector);
}
}
hotChange();
}
```
请注意,以上代码仅供参考,具体优化方式需要根据实际情况进行调整。
阅读全文