Native JS implements carousel plug-in for carousel pictures _ javascript skills

Source: Internet
Author: User
This article mainly introduces the information related to the implementation of the carousel plug-in by using native JS. If you need it, you can refer to my own three carousel images, one is implemented in simple native JS with no animation effect, and the other is implemented in combination with JQuery, with fade-in and fade-out switching. Now I want to make a cool job on a blog or personal website, so that I can present my work. After visiting MOOC, I found a jquery plug-in course with a carousel Trojan, which is cool, so I thought about encapsulating it with native JS. It is not as easy as you think... Don't worry. Let's explain the implementation process.

Ii. Results

Because your server is not ready yet. Online demonstration cannot be performed (ORZ...), but only one can be saved.

From the picture, we can still see the approximate effect. I will not say much about it. If you want to see the real code, please download the code on my github. Don't forget to give me a star in my github project.

Iii. Implementation Process

Html Structure

This structure is the same as the general carousel html code structure. A slight difference is that the main carousel p has a data-setting attribute, which contains some parameters of the carousel effect. The specific meanings of parameters will be explained later.

The code in the css part will not be pasted. The most important thing is to pay attention to the absolute positioning of elements. It can be seen that the positions and sizes of each image are different, so these are all controlled by js, therefore, absolute positioning is required. The following describes the js implementation process.

JS implementation process

The following describes several key JS steps. After completing these steps, there should be no difficulties.

① Default parameters

Since it is an encapsulation plug-in, some default values of parameters must be configured. This plug-in mainly has the following parameters:
Width: 1000, // The width of the slide area
Height: 400, // The height of the slide area
CarrouselWidth: 700, // width of the first frame of the slide
CarrouselHeight: 400, // height of the first frame of the slide
Scale: 0.9, // display the proportional relationship. For example, the size of the second image is smaller than that of the first image.
AutoPlay: true, // whether to play automatically
TimeSpan: 3000, // automatic playback Interval
VerticalAlign: 'middle' // picture alignment mode. top \ middle \ bottom is supported. The default value is middle.

② Encapsulate objects

Because a website may use the same carousel plug-in multiple places, encapsulation is critical. After this object is defined, if you can create multiple objects by defining an initialization method for the object, you only need to pass the same dom of all classes into it. Therefore, my initialization method is as follows:

Export usel. init = function (carrousels) {var _ this = this; // convert nodeList to array var cals = toArray (carrousels );
/* Because native JS gets all the classes, it gets a nodeList, which is an array of classes. If you want to use the array method, you need to convert it to a real array. ToArray is the conversion method. */Cals. forEach (function (item, index, array) {new _ this (item );});}

In this case, I call Carrousel. init (document. querySelectorAll ('. carrousel-main') during window. onload so that multiple carousel can be created!

③ Initialize the location parameter of the first frame

Because the parameters of all frames after the first frame are defined by reference to the first frame, it is critical to define the first frame.

SetValue: function () {this. carrousel. style. width = this. settings. width + 'px '; this. carrousel. style. height = this. settings. height + 'px ';/* set the left and right buttons. Here, let the left and right buttons evenly split the carousel area width minus the area after the first frame width, the value of z-index is higher than that of all images except the first frame, and the image is placed right or right. Therefore, the value of z-index is half the number of images. */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); // set this for the first frame. 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, the data-setting Parameter is obtained from the dom node, and the default parameter configuration is updated. Note that you cannot directly update the default parameters by assigning values to dom parameters, because all parameters may not be configured once when you configure the parameters. If you assign values directly, but not all parameters are configured, the parameters will be lost. Here, I wrote an object extension method similar to the $. extend method in JQuery to update parameters. If you are interested, you can download it.

④ Other Image Location settings

The image here is actually to divide the pictures except the first one evenly to the left and right sides, while the positions on the left are different from those on the right, so you need to configure them separately:

// Set the location relationship of the right image var rightIndex = level; rightSlice. forEach (function (item, index, array) {rightIndex --; var I = index; rw = rw * carrouselSelf. settings. scale; // the picture on the right is rh = rh * carrouselSelf. settings. scale; item. style. zIndex = rightIndex; // The smaller the value of zIndex to the right, the smaller the number of items can be gradually decreased. style. width = rw + 'px '; item. style. height = rh + 'px '; item. style. opacity = 1/(++ I); // The smaller the transparency to the right
// Here, the gap calculation method is: the carousel area minus the width of the first frame, except 2, and then the number of pictures on the left or right. style. left = (constOffset + (++ index) * gap-rw) + 'px '; // The left value 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. style. top = carrouselSelf. setCarrouselAlign (rh) + 'px ';});

The setting method on the left is similar and easier, so I will not elaborate on it.

⑤ Adjust the position and size of all images during rotation

This step is very important. Click the next button on the right to rotate left, and click the previous button on the left to rotate right. At this point, we only need to regard all the images as a ring, click once, and rotate the image at another position. When the rotation is left, make the second parameter equal to the first one, the third is equal to the second..., and the last is equal to the first one. When the right rotation is performed, make the first parameter equal to the second one, the second parameter equal to the third..., and the last parameter equal to the first one.

Let's talk about left-handed transfer.

If (dir = 'left') {toArray (this. carrouselItems ). forEach (function (item, index, array) {var pre; if (index = 0) {// determine whether it is the first pre = _ this. carrouselLat; // make the first pre equal to the last var width = pre. offsetWidth; // obtain 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 = tempZInde X; var opa = tempOpacity; var top = tempTop; var left = tempLeft;} // note that the second image references the first one, the first one is changed first, so the relevant parameters of the first one must be saved temporarily. 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 ;});});}

If some animations are not used too much, the rotation here will become very stiff. However, native JS does not have animation functions. Here I write an animation function that imitates it myself. The principle is to obtain the original dom style value and compare it with the new value. Define a speed using some methods. The speed here is to use the difference value of 18. Then define a timer. Refer to the time interval in jquery source code for execution every 13 milliseconds. Then, the timer is clearly displayed when the original style value is added with speed equal to the input value. For details, refer to here.

Well, the key points are almost the same. It should be easy to understand these processes!

Iv. Summary

Summary:

I personally think this is a plug-in that is better understood. It would be quite easy to do with JQuery. However, if we use native to write data, we still feel a little less fluent. It should be that custom animations are not as good as those encapsulated by JQuery.

Also, this plug-in requires that the image be evenly distributed to the left and right sides. For an even number of images, the method used here is to clone the first image and add it to the end to form an odd number.

Thoughts:

If there is a bug, I define a rotateFlag flag to determine whether the current rotation is possible, that is, to prevent the quick click from keeping up. When I press the button, set rotateFlag to false, and then set rotateFlag to true after the animation ends, but it seems that the role is not obvious. I hope you can give me some advice and make progress together.

The above is all the content of this article. For more information, refer to: javascript image carousel effect summary. Thank you for your reading.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.