jquery实现百叶窗效果

2020-05-24 21:39:03易采站长站整理

$(this).stop(true).animate({"left" : idx * 35}, 1000);
$(“img:lt( idx )“).each(function(){
$(this).stop(true).animate({"left" : ($(this).index()) * 35}, 1000)
})
});
})

看上去没有什么错误,见证奇迹~~~奇迹~~迹~~~然而并没有什么奇迹,原因就是  $(“img:lt( idx )“) 这种写法,里面的idx已经不是变量了,所以无法获取当前的 idx 值,我们可以在外面定义一个变量,同时用 + 连接 lt 和变量 idx,再把变量引入进去即可。

因此更改后如下:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<style type="text/css">
div{
width: 420px;
height: 186px;
border: 2px solid #ccc;
overflow: hidden;
position: relative;
margin: 100px auto;
}
img{
border: none;
display: block;
position: absolute;
top: 0;
}
img:nth-of-type(1){
left: 0;
}
img:nth-of-type(2){
left: 84px;
}
img:nth-of-type(3){
left: 168px;
}
img:nth-of-type(4){
left: 252px;
}
img:nth-of-type(5){
left: 336px;
}
</style>
<div class="box">
<img src="http://tupian.enterdesk.com/2013/mxy/10/12/1/17.jpg">
<img src="http://tupian.enterdesk.com/2013/mxy/07/0715/1/7.jpg">
<img src="https://www.easck.com/d/file/200524/20200524212506852.jpg">
<img src="https://www.easck.com/d/file/200524/20200524212506853.jpg">
<img src="https://www.easck.com/d/file/200524/20200524212506854.jpg">
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
var lefts;
var idx;
var imgL;
$("img").each(function(){
$(this).mouseenter(function(e) {
idx = $(this).index();
imgL = "img:lt(" + idx + ")"
lefts = idx * 35;
//当前图片的变化
$(this).stop(true).animate({"left" : idx * 35}, 1000);
$(imgL).each(function(){
$(this).stop(true).animate({"left" : ($(this).index()) * 35}, 1000)
})
});
})

这样奇迹就出现了~~ 同样的道理,右侧也是同样的方法。

最终代码如下:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<style type="text/css">
div{
width: 420px;
height: 186px;
border: 2px solid #ccc;
overflow: hidden;
position: relative;
margin: 100px auto;
}
img{
width:280px;
height:186px;
border: none;
display: block;
position: absolute;
top: 0;
}
img:nth-of-type(1){