輪播(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)
}