I have written three picture carousels myself. One is implemented in simple native JS and has no animation effects. The other is implemented in combination with JQuery and is switched in and out. Now I want to make a cooler one on my blog or personal website, and I can display my own works at that time. After a while shopping in MOOC, I found that there was a carousel jquery plug-in course, which was a bit cool, so I thought about encapsulating it in native JS. Only after doing it did it was not as easy as I thought. . . Let’s not talk about it anymore, let’s explain the implementation process.
2. Effect
Because my server has not been installed yet. There is no online demonstration (ORZ...), so I can only put a rendering.
The approximate effect can still be seen from the pictures, so I won’t say much. If you want to see the real code effect, welcome to my github download code. Don’t forget to give me a star in my github project^_^
III. Implementation process
html structure
<div data-setting='{"width":1000,"height":400, "carrouselWidth":750, "carrouselHeight":400, "scale":0.9, "verticalAlign":"middle"}'> <div></div> <ul> <li> <a href="#"><img src="img/1.jpg"></a> </li> <li> <a href="#"><img src="img/2.jpg"></a> </li> <li> <a href="#"><img src="img/2.jpg"></a> </li> <li> <a href="#"><img src="img/3.jpg"></a> </li> <li> <a href="#"><img src="img/4.jpg"></a> </li> <li> <a href="#"><img src="img/5.jpg"></a> </ul> <div></div> </div>This structure is the same as the html code structure of general carousels. The slight difference is that there is a data-setting property on the main carousel div, which contains some carousel effects parameters. The specific significance of the parameters will be explained later.
The code for the css part will not be posted. The most important thing is to pay attention to the absolute positioning of the elements. As can be seen from the renderings, the position and size of each image are different, so these are controlled through js, so absolute positioning is required. Let’s focus on the implementation process of js.
JS implementation process
Let’s talk about a few key steps in JS. After doing these steps, there should be no difficulties.
①Default parameters
Since it is a package plug-in, there will definitely be some default values for parameters that need to be configured. In this plugin, the following parameters are mainly:
width:1000, //Width of slide area
height:400, //The height of the slide area
carrouselWidth:700, //Width of the first frame of the slide
carrouselHeight:400, //The height of the first frame of the slide
scale: 0.9, //Record the scale relationship, for example, how much width and height of the second picture are smaller than that of the first picture when displayed.
autoPlay:true,//Is it automatically played?
timeSpan:3000,//Auto play time interval
verticalAlign:'middle' //Image alignment, there are three ways: top/middle/bottom, default is middle
②Encapsulate the object
Because a website may use the same carousel plug-in in multiple places, packaging is critical. After defining this object, if you define an initialization method for the object, you can create multiple objects. You just need to pass the same dom of all classes in it. So, my initialization method is as follows:
Carousel.init=function(carrousels){ var _this=this; //Convert nodeList to array var cals= toArray(carrousels); <br> /*Because native JS gets all classes, what you get is a nodeList, which is a class array. If you want to use an array method, you need to convert it into a real array. Here toArray is the conversion method. */ cals.forEach(function(item,index,array){ new _this(item); }); }In this way, when I am on window.onload, I call Carrousel.init(document.querySelectorAll('.carrousel-main')); this way I can create multiple carousels!
③Initialize the position parameters of the first frame
Because the relevant parameters of all frames after the first frame are defined with reference to the first frame, it is important to define the first frame well.
setValue:function(){this.carrousel.style.width=this.Settings.width+'px';this.carrousel.style.height=this.Settings.height+'px'; /*Left and left button settings, here, the area after the left and right buttons are subtracted from the width of the first frame. z-index is higher than all pictures except the first frame, and the pictures are just placed left and right, so the value of z-index is half of the number of pictures. */ var btnW=(this.Settings.width-this.Settings.carrouselWidth)/2; this.preBtn.style.width=btnW+'px'; this.preBtn.style.height=this.Settings.height+'px'; this.preBtn.style.zIndex=Math.ceil(this.carrouselItems.length/2); this.nextBtn.style.width=btnW+'px'; this.nextBtn.style.height=this.Settings.height+'px'; this.nextBtn.style.zIndex=Math.ceil(this.carrouselItems.length/2); //The first frame related settings this.carrouselFir.style.left=btnW+'px'; this.carrouselFir.style.top=this.setCarrouselAlign(this.Settings.carrouselHeight)+'px'; this.carrouselFir.style.width=this.Settings.carrouselWidth+'px'; this.carrouselFir.style.height=this.Settings.carrouselHeight+'px'; this.carrouselFir.style.zIndex=Math.floor(this.carrouselItems.length/2);},Here, when the new object is used, go to the dom node to get the data-setting parameters and then update the default parameter configuration. There is a place to note here. You cannot directly update the default parameters by assigning values when obtaining the parameters, because when users configure parameters, all parameters may not be configured once. If the value is assigned directly and the user happens to be configured, the parameters will be lost. Here I wrote an object extension method similar to the $.extend method in JQuery to update parameters. I won't list the details, if you are interested, you can download it.
④Other picture location settings
The picture here is actually the picture except the first one is divided into two left and right pictures, and the picture position on the left and the one on the right is different, so it needs to be configured separately:
//Set the positional relationship of the picture on the right var rightIndex=level;rightSlice.forEach(function(item,index,array){ rightIndex--; var i=index; rw=rw*carrouselSelf.Settings.scale; //The picture on the right is gradually smaller according to the scale ratio rh=rh*carrouselSelf.Settings.scale; item.style.zIndex=rightIndex;//The value of z-index on the right is smaller, and the number of pictures can be gradually decreased by using the general number of pictures item.style.width=rw+'px'; item.style.height=rh+'px'; item.style.height=rh+'px'; item.style.opacity=1/(++i);//The more you go to the right, the less transparency<br> //The gap calculation method here is: subtract the first frame width, divide 2, and then divide the number of pictures on the left or right item.style.left=(constOffset+(++index)*gap-rw)+'px';//The value of left is actually the left of the first frame + the width of the first frame + the spacing of the item minus the width of the item item.style.top=carrouselSelf.setCarrouselAlign(rh)+'px';});The setting method on the left is similar and simpler, so I won't go into details.
⑤ Adjust the position size of all pictures during rotation
This step is very important. Clicking the next one on the right button is the left rotation, and clicking the previous one on the left button is the right rotation. At this time, we only need to regard all the pictures as a ring, click once, change the position and complete the rotation. Specifically when the left rotation is turned, make the parameters of the second picture equal to the first picture, the third picture equal to the second picture... and the last picture equal to the first picture. When rotating right, make the parameter of the first picture equal to the second picture, the parameter of the second picture equal to the third picture... and the parameter of the last picture equal to the first picture.
Let's talk about left rotation here
if(dir=='left'){ toArray(this.carrouselItems).forEach(function(item,index,array){ var pre; if(index==0){//Judge whether it is the first pre=_this.carrouselLat;//Save the first pre equal to the last var width=pre.offsetWidth; //Get the corresponding parameter var height=pre.offsetHeight; var zIndex=pre.style.zIndex; var opa=pre.style.opacity; var top=pre.style.top; var left=pre.style.left; }else{ var width = tempWidth; var height = tempHeight; var zIndex = tempZIndex; var opa = tempOpacity; var top = tempTop; var left = tempLeft; } //Note here, because the second picture refers to the first picture, and when changing in this way, the first picture is changed first, so the relevant parameters of the first picture must be temporarily saved. tempWidth = item.offsetWidth; tempHeight = item.offsetHeight; tempZIndex = item.style.zIndex; tempOpacity = item.style.opacity; tempTop = item.style.top; tempLeft = item.style.left; item.style.width=width+'px'; item.style.height=height+'px'; item.style.zIndex=zIndex; item.style.opacity=opa; item.style.top=top; // item.style.left=left; animate(item,'left',left,function(){//Custom native js animation function_this.rotateFlag=true; }); });}The rotation here will appear stiff if you don't use some animations too much. But native JS does not have animated functions, here I wrote an imitated animation function myself. The principle is to get the original style value of the dom and compare it with the newly passed value. Use some methods to define a speed. My speed here is to divide the difference of 18. However, define a timer, and refer to the time interval in the jquery source code to execute every 13 milliseconds. Then, the timer is clear every time the original style value is added to the incoming value. For details, please see here.
Okay, the key points are almost the same, and it should be easy if you understand these processes!
4. Summary and reflection
Summarize:
I personally think this is a relatively easy-to-understand plugin. It would be quite simple to do it in combination with JQuery. However, if you write from the original, you still feel a little less smooth. It should be that custom animations are not as good as the animations encapsulated by JQuery.
Also, because the images need to be divided equally on both sides of the left and right sides, for even numbers of pictures, the method used here is to clone the first picture, then add it to the end, and form an odd number.
think:
If there is a bug, it means that I define a rotateFlag flag to determine whether it can rotate at the moment, which is to prevent you from keeping up with the fast click. When I pressed, I set rotateFlag to false, and then set rotateFlag to true after the animation ended, but it seems that the effect is not obvious. I hope the relevant masters can give me some advice and everyone will make progress together.
The above is the entire content of this article. For more content, please refer to: Summary of javascript picture carousel effects. Thank you for your reading.