**
自动切换焦点图片——原生JS
**
注释很详细!!!
有兴趣的可以找我拿素材!!!以下是代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="自动切换焦点图片.css"/>
</head>
<body>
<div class="WrapperBox">
<div class="pointer">
<img id="pointer" src="pointer.png" >
</div>
<div class="top_image" id="top_image">
<img src="1.jpg" alt="">
<img src="2.jpg" alt="">
<img src="3.jpg" alt="">
</div>
<div class="bottom_image" id="bottom_image">
<img class="active" src="1.jpg" alt="">
<img src="2.jpg" alt="">
<img src="3.jpg" alt="">
</div>
</div>
</body>
</html>
<script src="自动切换焦点图片.js" type="text/javascript" charset="utf-8"></script>
*{
margin: 0;
padding: 0;
text-decoration: none;
list-style: none;
}
.WrapperBox{
margin-top: 10px;
position: relative;
}
.top_image{
width:1110px;
margin: 0 auto;
}
.bottom_image{
width: 920px;
height: 500px;
overflow: hidden;
margin: 0 auto;
}
.top_image img{
width: 350px;
height: 200px;
float: left;
margin: 0 10px;
cursor: pointer;
}
.top_image::after{
content: '';
display: block;
clear: left;
}
.bottom_image img{
margin-top: 10px;
width: 920px;
height: 500px;
display: none;
}
.pointer{
position: relative;
width: 1110px;
margin: 0 auto;
}
.pointer img{
position: absolute;
left: 0px;
width: 380px;
height: 203px;
}
.active{
display: block !important;
}
var topImage = document.getElementById('top_image').getElementsByTagName('img'),//获取上图片
bottomImage = document.getElementById('bottom_image').getElementsByTagName('img'),//获取下图片
pointer = document.getElementById('pointer');//获取pointer图片
for(var i = 0;i < topImage.length;i++){
topImage[i].onmouseenter = function(){
for(var j = 0;j < bottomImage.length;j++){
if(topImage[j] == this){
// bottomImage[j].className = 'active';
StartLocation = pointer.offsetLeft;//赋值一个开始位置,开始位置根据pointer位置计算。
EndLocation = topImage[j].offsetLeft;//赋值目标位置。目标位置根据移上的那个图片位置计算。
EndLocation = EndLocation - 223;//由于css样式所产生的误差
if(interval == null){
interval = setInterval(MoveTo,20);//启动定时器
}
}else{
// bottomImage[j].className = '';
}
}
}
}
var speed = 8,//速度
StartLocation = 0,//开始位置
EndLocation = 0,//结束位置
interval = null;
function MoveTo(){
if(StartLocation < EndLocation){//代表向右移动
StartLocation += speed;
if(StartLocation >= EndLocation){//向右移动时,当开始位置大于等于结束位置时,代表执行完毕!
StartLocation = EndLocation;
clearInterval(interval);//清空计时器
interval = null;
}
}else if(StartLocation > EndLocation){//代表想左移动
StartLocation -= speed;
if(StartLocation <= EndLocation){//向左移动时,当开始位置小于等于结束位置时,代表执行完毕!
StartLocation = EndLocation;
clearInterval(interval);
interval = null;
}
}
pointer.style.left = StartLocation + 'px';//开始移动
if(StartLocation == EndLocation){//当到达目的地的时候,代表图片可以显示了。
for(var i = 0;i < topImage.length;i++){
if(pointer.offsetLeft == topImage[i].offsetLeft - 223){//根据位置判断应该显示第几张图片?
bottomImage[i].className = 'active';
}else{
bottomImage[i].className = '';
}
}
}
}