jQuery-网格手风琴练习demo代码
jQuery实现一个手风琴,图片可以自动循环滚动,宽高和定位同时变化,当鼠标移上时当前图片最大,同一排的图片高度一致,同一列的宽度一致,鼠标离开继续滚动。
思路:结构直接用多个div,图片使用背景图,通过定位设置每一行每一列的位置,设置鼠标当前位置为一个变化量,通过这个变化量来设置其他div的宽高和定位。
- html和css
#accordion{
width: 500px;
height: 500px;
margin: 100px auto;
border: 3px solid #fff;
position: relative;
overflow: hidden;
}
#accordion .img{
width: 100px;
height: 100px;
border-right: 3px solid #fff;
border-bottom: 3px solid #fff;
position: absolute;
left: 0;
top: 0;
overflow: hidden;
}
<div id="accordion">
<div class="img"></div> //这里有25个div
</div>
- js部分
1.获取元素和定义变化量
var $accordion = $("#accordion");
var $images = $accordion.find(".img");
var currentIndex = 0;
2.定义初始状态,每个div宽高100,定位值根据索引值和5的余数关系,除5余数相同的为同一列(0,5,10,15,20),(1,6,11,16,21)...所以left值相同;每一排的值(0-4,5-9,10-14...)除5得到的值取整之后相同,分别为0,1,2,3,4。
$images.each(function(index){
$(this).css({
"width": 100,
"height": 100,
"left": index % 5 * 100,
"top": parseInt(index / 5) * 100
});
});
3.封装设置每个元素样式的函数,函数中根据遍历每一个元素的索引值index和设置的变化量currentIndex的比较情况,设置样式。
function setAllEle(){
$images.each(function(index){
$(this).stop(true).animate({
//索引值除5的余数若等于当前变化量除5的余数则表示同一列,宽度统一200,其他列75
"width": index % 5 == currentIndex % 5 ? 200 : 75,
//高度通过除5取整判断是否为同一排
"height": parseInt(index/5) == parseInt(currentIndex/5) ? 200 : 75,
//除5余数大于当前的列,left值等于余数减1乘以75,再加一个当前的宽度200;小于当前列的就直接等于索引值除5的余数乘以75
"left": index % 5 > currentIndex % 5 ? 200 + (index % 5 - 1) * 75 : index % 5 * 75,
//top值和left值类似,判断在当前排的上方还是下方,下方等于取整后减1乘以75,而在上方的就直接等于取整的值乘以75
"top": parseInt(index / 5) <= parseInt(currentIndex / 5) ? parseInt(index / 5) * 75 : 200 + (parseInt(index / 5) - 1) * 75
}, 1000);
});
}
有一点点绕,不过结合图图就一目了然了,这种通过一个变化量来设置其他元素的方式,关键就是找到当前元素和其他元素之间的关系,利用关系式来设置样式。
4.添加鼠标进入和离开的事件监听
$accordion.delegate(".img","mouseenter",function(){
//将时间委托给$accordion,如果给每一个div添加事件页面效果不好,因此使用jQuery的时间委托delegate把时间设给最外层的div
//鼠标进入后清除定时器
clearInterval(timer);
currentIndex = $(this).index();
setAllEle();
});
$accordion.mouseleave(function(){
//鼠标离开后重启定时器
timer = setInterval(function(){
setAllEle();
currentIndex++;
if(currentIndex>24) currentIndex=0;
}, 1000);
});
5.设置定时器
var timer = setInterval(function(){
setAllEle();
currentIndex++;
//信号量超过24之后置0重新开始累加
if(currentIndex>24) currentIndex=0;
}, 1000);
作者:ACodingIceBear
THE END