轮播(4)
轮播-手风琴(四)
1, 需求,
在之前的三个轮播图之上,继续完善轮播类型之轮播图-手风琴
2, 原理
动态缓慢的改变图片的宽度,缓慢移动的代码被抽离出来,放在util.js文件中,方便其他轮播使用,轮播中所用到的图片依然用颜色代替,
3, 代码(index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手风琴</title>
<style>
ul{list-style: none;}
* {margin: 0px; padding: 0px;}
div {
width: 1150px;
height: 400px;
margin: 50px auto;
border: 1px solid red;
overflow: hidden;
}
div ul {
width: 1300px;
}
div li {
width: 240px;
height: 400px;
float: left;
}
div li:nth-child(1) {
background-color: red;
}
div li:nth-child(2) {
background-color: blue;
}
div li:nth-child(3) {
background-color: pink
}
div li:nth-child(4) {
background-color: chartreuse;
}
div li:nth-child(5) {
background-color: darkcyan;
}
</style>
<script src="./util.js"></script>
</head>
<body>
<div id="box">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
<script>
var box = document.getElementById('box')
var ul = box.children[0]
var liArr = ul.children;
for (var i =0; i<liArr.length; i++) {
liArr[i].onmouseenter = function() {
for(var j=0; j<liArr.length;j++) {
lowSpeedAnimate(liArr[j],{"width": 100}); // 所有列变窄
}
slowSpeedAnimate(this,{"width": 800});
}
}
box.onmouseleave = function() {
for(var i =0; i< liArr.length; i++) {
slowSpeedAnimate(liArr[i], {'width':240});
}
}
</script>
</html>
util.js (封装动画), 后续所有的轮播,都会用到这个JS
/*
* @Description: 工具函数
* @Version: 1.0
*/
/**
* @description 获取行内和内嵌样式,兼容性写法封装
* @param {目标元素} ele
* @param {元素属性} attrName
*/
function getStyle(ele, attrName) {
if(window.getComputedStyle) {
return window.getComputedStyle(ele, null)[attrName];
}
return ele.currentStyle[attrName];
}
/**
* @description 缓动动画函数封装
* @param {目标元素} ele
* @param {所需的样式文本} json
* @param {*} callback
*/
function slowSpeedAnimate(ele, jsonText, callback) {
clearInterval(ele.timer)
ele.timer = setInterval(function() {
var boo = true
for(var item in jsonText) {
var nowState;
if (item === 'opacity') {
nowState = parseInt(getStyle(ele, item) * 100) || 100;
console.log('ke',nowState)
} else {
nowState = parseFloat(getStyle(ele, item)) || 0;
nowState = Math.round(nowState)
}
var step = (jsonText[item] - nowState) /10;
step = step > 0 ? Math.ceil(step): Math.floor(step);
nowState = nowState + step;
if (item === 'opacity') { // 开始移动
ele.style[item] = nowState / 100;
ele.style.filter = "alpha(opacity=" + nowState + ")"; // 兼容IE
} else if (item === 'zIndex') {
ele.style[item] = jsonText[item];
} else {
ele.style[item] = nowState + 'px';
}
if(nowState !== jsonText[item]) { // 到达终点,停止定时器
boo = false
}
}
if (boo) {
clearInterval(ele.timer)
if(typeof callback === 'function') {
callback();
}
}
},30)
}