In my opinion, to implement a carousel, it is mainly to know the page currently and the page that will be located. This case is to achieve the effect of carousel by changing the transparency of the picture.
I divided the knowledge points involved into two aspects, namely HTML+css and JS.
Part One(html+css)
The knowledge contained is: positon positioning.
The outermost layer is a div that contains all the elements. There are three images in this carousel, and these three images are included in an unordered list. The outermost div also has two sub-elements used to switch between the previous picture and the next picture. These two child elements are also divs. Switch the id attribute of the div of the previous picture to pre, and switch the id attribute of the div of the next picture to next. The position value of the outermost div is relative. The position of the unordered list of images is relative. The positon attribute value of the li element in the unordered list is absolute, which will allow the li element to be outside the document stream, so if the height of the setting ul is not displayed, the height of the ul is zero. But we cannot use css to display the height of the set ul. Because the height of this carousel is equal to the height of the picture, and the aspect ratio of the picture remains unchanged on computers with different resolutions. The height and width displayed by pictures on computers of different resolutions are different. So I set the height of ul through js. Because the attribute value of ul position is relative, ul's height will extend the height of the outer div. Since this case carousel is achieved by changing the transparency of the picture, all pictures are located in the same position. By default, the last picture will be at the top and the first picture is at the bottom. The first picture displayed in the carousel should be the first picture, then the second picture, and finally the third picture, so set the z-index attribute for each li to be displayed. And the z-index attribute values are decreasing in turn. I use js to set the z-index attribute value of each li, but there is actually no need to do this. Just use the css attribute directly, but I have to write three selectors.
The html is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Carousel by changing transparency</title> <link rel="stylesheet" type="text/css" href="" rel="external nofollow" > </head> <body> <div class='warp' id='warp'> <ul class='list' id='list'> <li><img src='img/' style='opacity: 1'></li> <li><img src='img/' style='opacity: 1'></li> <li><img src='img/' style='opacity: 1'></li> </ul> <div class='pre' id='pre'>《</div> <div class='next' id='next'>》</div> </div> <script type="text/javascript" src=''></script> </body> </html>
The css code is as follows
*{ padding: 0; margin: 0; } .warp{ position: relative; width: 100%; } .list{ position: relative; width: 100%; } .list li{ position: absolute; top:0; left: 0; width: 100%; list-style: none; opacity: 1; } li img{ width: 100%; } .pre,.next{ position: absolute; top: 50%; bottom: 0; width: 64px; height: 64px; z-index: 10; margin-top: -32px; text-align: center; line-height: 64px; color: #fff; font-weight: bold; font-size: 30px; cursor: pointer; background-color: transparent; } .pre{ left: 20px; right: auto; } .next{ right:20px; left: auto; } .pre:hover,.next:hover{ background-color: rgba(0,0,0,0.7); }
Part 2(js)The knowledge involved include: events, function throttling, setting timers, clearing timers
Since events use native JS to implement functions, browser compatibility issues need to be considered.
Event flow
There are two types of time flows, namely event bubble flow and event capture flow. This is almost the opposite concept of event flow. Event bubble flow is called event bubble, which is proposed by IE. Taking a click event as an example, in the event bubble, the event first occurs on the most specific element, that is, the element we click, and then propagates up along the dom tree. During the propagation process, a click event will occur at each level of node until the propagated document object. Event capture streams are called event capture, which was proposed by Netscape Communicator. Take a click event as an example. In event capture, the event first occurs on the least specific node (the document object first receives the event), and then propagates down the dom tree. The most specific node finally receives the event, that is, the element actually clicked finally receives the click event. "DOM2 level event" stipulates that the event flow includes three stages, namely the event capture stage, which is in the target stage and the event bubble stage. In mainstream browsers, except for IE, which does not support DOM event streams, other browsers support DOM event streams. So the support events of IE are bubbled up. However, in the future, IE should support DOM event streaming. At that time, when binding events, you don’t have to consider browser compatibility issues. Currently, in order to be able to be compatible with various browsers, I add event handlers to the bubbling phase of the event stream.
Event handler
》DOM0 level event handler
The DOM0 level binds events by assigning values to the element's attributes, and sets the value of the event handler attribute to a function. This in the program refers to the current element. The method of deleting event bound by the DOM0 level method is: set the attributes of the event handler to null. If an element binds an event, it is best to manually unbind the event of this element before removing the document. This prevents the element from being removed but the reference to the event handler of the element remains in memory. Therefore, modern browsers support DOM0 level event handlers. However, when using DOM0 level to bind events, only one event handler can be added to each element for the same event.
》DOM2 level event handler
The method for specifying an event handler in "DOM2 level event" is: addEventListener(), the first parameter is an event name, the second parameter is an event handler (that is, a function, which can be an anonymous function), and the third parameter is a boolean value. This boolean value indicates at which stage the event is processed, when false, it indicates processing in the bubble stage, and when true, it indicates processing in the capture stage. For compatibility I set this value to false. To unbind the time handler with "DOM2 level event", removeEventListener() is required. The anonymous event handler cannot be unblocked. When binding events with "DOM2 level events", multiple event handlers can be added to each element for the same event. An event handler kidnapped with "DOM2 level event", this refers to the current element.
》IE event handler
The method of specifying an event handler in IE is attachEvent(), the first parameter is the event handler name (i.e. "on" + event name), and the second parameter is the time handler (a function, which can be an anonymous function). Since IE only supports event bubbles, events are processed in the bubble phase. Use detachEvent() to remove the time handler added with attachEvent(), but the anonymous function cannot be removed. Use attachEvent() to bind the event this refers to window. . When binding events with attachEvent, multiple event handlers can be added to each element for the same event.
Note:The reason why anonymous functions cannot be removed is that in js the function is an object, which is stored in the heap, and the function name is a pointer, pointing to the object in the heap. For an anonymous function there is no pointer to it, so it cannot be accessed.
Event Object
In a DOM-compatible browser, the event object is passed as a parameter into the event handler. (That is, in DOM-compatible browsers, whether they bind events through DOM0 or DOM2 levels, the event object will be passed as parameters to the event handler). At that time, in the IE browser, if the time handler is specified with DOM0 level, the event object is saved in the event property of the window. If the time handler is specified with attachEvent(), the event object is passed as a parameter to the event handler. There is a difference between the value in the event object of a DOM-compatible browser and the value in the event object of an IE. But they all have a common value - type (i.e. the type of time that was triggered). In a DOM-compatible browser, the target attribute of the event object represents the target of the event. Taking a click event as an example, the target attribute refers to the most specific element. In IE browser, the srcElement property of the event object represents the event target
In this case, I added a click event handler for the outermost div (its id is warp). Determine the node that triggers the event by judging the id value of the event target. If the id value of the event target is pre, switch to the previous picture, and if the id value of the event target is next, switch to the next picture. Here is an event proxy, which can reduce the memory used.
Function throttlingFunction throttling is used in this case to reduce the amount of calculations of the browser when the resize event is triggered continuously, because if the browser's calculations are too large, the browser will slow down and even crash. The main idea of function throttling is that when an event is triggered, in the event handler, it is not to do the calculation immediately, but to use setTimeout or setInterval to perform the calculation after the specified time.
Setting timer and clearing timerSince we need to fully explain the timer and also involve single-thread execution of browser threads and js, we will not explain it now. The main reason is that I haven't fully understood it yet. Let me mention that the browser is multi-threaded. Turning on the timer is the timer thread in the browser, and the js executor is another thread in the browser. The browser has no other threads except these two threads. I will write another article after I understand the connection between browser threads.
In this example, changing the transparency of the picture is to gradually increase or decrease by setting the timer. Before increasing the opacity of the next image, reduce the opacity of the current image to 0.
Open the page to play automatically, which is also achieved by using a timer. If you want to stop playing, clear the timer.
The js code is as follows
// When the page is loaded, add the function that needs to be executed to the load event of the window. This is used to bind dom0-level events, so you cannot add multiple event handlers to the load event of the window. So the method used is: first determine whether there is a bound function. If it is bound, append the new function to the tail. If there is no binding, add it directly to it. Use attachEvent() or addEventListener() to bind multiple event handlers for the same event of the same element, and you can do not use the following method. function addLoadEvent(func){ var oldLoad = ; if(typeof oldLoad != 'function'){ = func(); }else{ = function(){ oldLoad(); func(); } } } //Set the height of class to list, because the position of the image is absolute, so the height of the .list element is zero//If the height of a parent element is 0, then setting the margin of this element: auto 0; does not workfunction setListHeight(){ var list = ('list'); var imgItem = ('img')[0]; var height = ; var list = ('list'); = height + 'px'; } // Set the level of Li, you can use css to set itfunction setLiIndex(){ var list = ('list'); var li = ('li'); var liLen = ; for(var i = 0;i<liLen;i++){ li[i]. = liLen-i; } } var index = 1;//index represents the currently displayed page, index is a global variablevar timer;// Timer identifier, if you want to clear the timer, you need to use it // Cross-browser bound object of eventvar untilEvent = { addEvent:function(element,type,hander){ if(){ (type,hander,false); }else if(){ ('on'+type,hander); }else{ element['on'+type] = hander; } }, getEvent:function(event){ return event?event:; }, getTarget:function(event){ return ||; } }; function btnClick(){ var warp = ('warp'); (warp,'click',function(event){ var event = (event); var target = (event); switch(){ case 'pre': if(index == 1){//If the currently displayed image is already the first image, when clicking the "Previous" button, set the upcoming image to the last image index =3; }else{ --index; } anmitate(); break; case 'next':if(index == 3){//If the currently displayed image is already the last image, when clicking the "Next" button, set the upcoming image to be displayed as the first image index = 1; }else{ ++index; } anmitate(); break; } }); } //Reduce image transparencyfunction decline(cur,inverTime,inverOpacity){ var opacityed = parseFloat(); if(opacityed > 0){ = opacityed-inverOpacity; setTimeout(function(){ decline(cur,inverTime,inverOpacity); },inverTime); } } //Switch the function of the picturefunction anmitate(){ var list = ('list'); var imgs = ('img'); var imgsLen = ; var whole = 300;//It takes time to switch a picture var inverTime = 5;//Time interval var inverOpacity = 1/(whole/inverTime); for(var i = 0;i<imgsLen;i++){ decline(imgs[i],inverTime,inverOpacity); } var go = function(){ var opacityed = parseFloat(imgs[index - 1].); if(opacityed < 1){ imgs[index-1]. = opacityed + inverOpacity; setTimeout(go,inverTime); } }; go(); } //Open the page and switch the function automaticallyfunction play() { timer = setTimeout(function () { if(index == 3){ index = 1; }else{ ++index; } anmitate(); play(); // }, 3000); } //Stop switching function, cancel the automatic switching after the mouse moves to the carousel, and when the mouse moves away from the carousel, it starts automatic switching againfunction stop() { clearTimeout(timer); } //Add mouse removal and mouse movement into event handler to the outermost divfunction getWarp(){ var warp = ('warp'); (warp,"mouseout",play); (warp,"mouseover",stop); } //Function throttling. When the window size is changed, the size of the picture will change. Therefore, in order to make the control button located in the middle of the vertical direction of the carousel, the height of li should change with the size of the picture.function scrollEvent(){ (window,"resize",function(){ throttle(setListHeight); }); } function throttle(method,context){ clearTimeout(); = setTimeout(method,70); } addLoadEvent(scrollEvent); addLoadEvent(setListHeight); addLoadEvent(setLiIndex); addLoadEvent(btnClick); addLoadEvent(play); addLoadEvent(getWarp);
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.