Home > Article > Web Front-end > Pure js code to implement accordion effects
I know that most front-end developers are now using third-party libraries such as jQuery for development. This not only saves time, but also greatly improves efficiency and increases the company's benefits. Why not?
However, this will also have certain shortcomings. For example, jQ is slower than js, which will appear especially in large projects. Below I use native js to implement a simple accordion effect.
The HTML code is as follows
The structure is very simple, just 5 li boxes, the js code will render the picture
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="box"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </body> </html>
The CSS code is as follows:
Please set the width and height by yourself. The picture of this project I did before was 1226*446 Pictures, so the width and height are set according to the time when working on the project. If you want to place pictures of other sizes, please install them according to the actual situation...
ul { list-style: none } * { margin: 0; padding: 0; } div { width: 1150px; height: 400px; margin: 50px auto; border: 1px solid red; overflow: hidden; } div li { width: 240px; height: 400px; float: left; /*background-image: url(images/1.jpg);*/ } div ul { width: 1300px; }
The following is the highlight, please enjoy the native js (I believe many people Forget native js)
//Find someone
var box = document.getElementById("box");
var ul = box.children[0];
var lis = ul.children;
// Loop through lis and bind the background image
for (var i = 0; i lis[i].style.backgroundImage = "url(images/" + (i + 1) + ". jpg)";
//Register the mouse pass event for each li. After the mouse passes, it must be exclusive
lis[i].onmouseover = function () {
//Kill everyone so that the width of everyone gradually becomes 100
for (var j = 0; j animate(lis[j], {"width": 100});
}
} Gradually becomes 800
animate(this, {"width": 800});
};
}
//The mouse leaves the box and all li widths gradually become 240
box.onmouseout = function () {
for (var i = 0; i animate(lis[i], {"width": 240});
}
};
//There is an animate animation function in jQuery , the following is the principle of implementation. Although it is not as powerful as jQ, there is still no problem in realizing the basic effect
function animate(obj, json) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {假 // First assume that all the attributes have reached the target this time. ;
var target = json[k];
var step = (target - leader) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
leader = leader + step;
using console.log("The code is still running ");
It means everyone has really arrived.
if ( window.getComputedStyle) {
return window.getComputedStyle(obj, null)[attr];
} else {
return obj.currentStyle[attr];
}
}
The above is all the code, you can find five Try the pictures.