代码需要多敲多练才能越来越熟练,才能不断的挖掘出代码的深层用法!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片切换</title>
<style type="text/css">
img{
width: 200px;
height: 160px;
margin-left: 10px;
}
div{
width: 300px;
border: 3px solid grey;
}
ul li{
list-style:none;
border: 1px solid black;
width: 20px;
margin-top:6px;
margin-right: 10px;
text-align: center;
}
div ul{
float: right;
}
</style>
<script type="text/javascript">
//页面加载触发定时器
window.onload=timer;
//控制图片顺序
var i = 1;
//定时器变量名
var timper;
// 定时器函数
function timer(){
var li1 = document.getElementById('li1');
li1.style.background='orange';
// 每秒切换一张图片
timper = window.setInterval('images()',1000);
}
//控制图片切换范围
function images(){
i++;
if(i > 5 ){
i=1;
}
var img= document.getElementById('img');
//修改src属性的值
img.src = 'images/'+ i +'.jpg';
color1();
var color2 = document.getElementById('li'+i);
color2.style.background='orange';
}
//当鼠标悬停图片则停止图片切换
function stopImg(){
window.clearInterval(timper);
}
//当鼠标离开则开始图片切换
function startImg(){
timper = window.setInterval('images()',1000);
}
//鼠标移至相应的li上,展示对应图片函数
function stopLi(n){
var img = document.getElementById('img');
var m = n.innerHTML;
i=m; //使图片切换传进来的参数保持一致
img.src = 'images/'+ m +'.jpg';
window.clearInterval(timper);
color1();
//将鼠标悬停的li背景色变为橘色
n.style.background='orange';
}
function startLi(n){
timper = window.setInterval('images()',1000);
}
//清除所有标签的背景颜色
function color1(){
for(var j =1; j<=5; j++){
var arrLi = document.getElementById('li'+j);
arrLi.style.background='';
}
}
</script>
</head>
<body>
<div>
<img src="images/1.jpg" id="img" onmouseover="stopImg()" onmouseout="startImg()">
<ul>
<li id="li1" onmouseover="stopLi(this)" onmouseout="startLi(this)">1</li>
<li id="li2" onmouseover="stopLi(this)" onmouseout="startLi(this)">2</li>
<li id="li3" onmouseover="stopLi(this)" onmouseout="startLi(this)">3</li>
<li id="li4" onmouseover="stopLi(this)" onmouseout="startLi(this)">4</li>
<li id="li5" onmouseover="stopLi(this)" onmouseout="startLi(this)">5</li>
</ul>
</div>
</body>
</html>