打开页面时会自动切换,当鼠标放在页面i上时下面图标不会切换,显示对应页面的图片,鼠标离开时自动切换
但鼠标离开时,切换会有延时,这是因为定时器的设置产生的,感觉怪怪的
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tab切换案例</title>
<style type="text/css">
*{margin: 0;padding: 0;}
li{
float: left;
width: 125px;
height: 50px;
list-style: none;
text-align: center;
line-height: 50px;
}
#outer{
width: 500px;
height: 300px;
background: #F6F1D4;
margin: 50px auto;
overflow: hidden;
}
ul{
width: 500px;
height: 50px;
background: #FFCC66;
}
#inner{
width: 500px;
height: 250px;
background: #CCFFCC;
}
p{background: #F6F1D4;}
img{
margin-top: 20px;
margin-left: 80px;
}
</style>
</head>
<body>
<!--tab切换案例-->
<div id="outer">
<ul>
<li>页面1</li>
<li>页面2</li>
<li>页面3</li>
<li>页面4</li>
</ul>
<div id="inner">
<img src="img/lehuo01.png" />
<p>页面1的内容</p>
</div>
<span>页面1的内容</span>
<span>页面2的内容,嘿嘿嘿</span>
<span>页面3的内容,呀呀呀</span>
<span>页面4的内容,哈哈哈</span>
</div>
<script>
var oLi = document.getElementsByTagName("li");
var oInner = document.getElementById("inner");
var oP = document.getElementsByTagName("p");
var img = document.getElementsByTagName("img")[0];
var span = document.getElementsByTagName("span");
function change(domObj,index){
domObj.style.backgroundColor = "#FFFF99";
img.src = "img/lehuo0"+(index+1)+".png";
oP[0].innerHTML = span[index].innerHTML;
for(var i = 0; i < oLi.length; i++){
if(oLi[i] != domObj){
oLi[i].style.background = "#FFCC66";
}
}
}
function changeText(domObj,index){
domObj.onmousemove = function(){
change(domObj,index);
}
}
function fn(){
change(oLi[count],count);
count++;
if(count > 3){
count = 0;
}
}
var timer = setInterval(fn,1000);
var count = 0;
//为什么这个for循环不能实现下面的代码
//已经实现,就是因为里面的for循环会先执行,事件里面的j会先一直加,等到执行事件时,j已经溢出
//函数里面的this指向调用的它的对象,所以这里可以使用this来解决这个bug
for(var j = 0; j < oLi.length; j++){
oLi[j].index = j; //刚开始没有写这行
oLi[j].onmouseover = function(){
clearInterval(timer);
//changeText(oLi[j],j);之前直接用了j,j溢出了所以报错
changeText(this, this.index);
}
oLi[j].onmouseout = function(){
//count = j;
count = this.index;
timer = setInterval(fn,1000);
}
}
/*oLi[0].onmouseover = function(){
clearInterval(timer);
changeText(oLi[0], 0);
}
oLi[0].onmouseout = function(){
count = 0;
timer = setInterval(fn,1000);
}
oLi[1].onmouseover = function(){
clearInterval(timer);
changeText(oLi[1], 1);
}
oLi[1].onmouseout = function(){
count = 1;
timer = setInterval(fn,1000);
}
oLi[2].onmouseover = function(){
clearInterval(timer);
changeText(oLi[2], 2);
}
oLi[2].onmouseout = function(){
count = 2;
timer = setInterval(fn,1000);
}
oLi[3].onmouseover = function(){
clearInterval(timer);
changeText(oLi[3], 3);
}
oLi[3].onmouseout = function(){
count = 3;
timer = setInterval(fn,1000);
}*/
</script>
</body>
</html>