English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Esempio di slide show HTML5 di base in JavaScript (44)

This article shares the specific code for the html5 carousel with everyone for reference, and the specific content is as follows

1. Carousel layout:

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8"> 
    <title></title> 
    <style type="text/css"> 
      /*去除默认样式*/ 
      *{ 
        margin: 0; 
        padding: 0; 
      } 
      /*设置div*/ 
      #outer{ 
        width: 520px; 
        height: 333px; 
        /*设置居中*/ 
        margin: 50px auto; 
        /* 
         * 设置背景颜色 
         */ 
        background-color: greenyellow; 
        /*设置上下内边距*/ 
        padding: 10px 0; 
        /*为父元素开启相对定位*/ 
        position: relative; 
        /*隐藏溢出的内容*/ 
        overflow: hidden; 
      } 
      /*设置ul*/ 
      #imgList{ 
        /*去除项目符号*/ 
        list-style: none; 
        /*设置ul的宽度*/ 
        width: 2600px; 
        /*开启绝对定位*/ 
        position: absolute; 
        /* 
         * 通过修改ul的left值,可以切换图片 
         * 1 0px 
         * 2 -520px 
         * 3 -1040px 
         * 4 -1560px 
         * .... 
         */ 
        left: 0px; 
      } 
      /*设置li*/ 
      li{ 
        /*设置元素浮动*/ 
        float: left; 
        /*设置外边距*/ 
        margin: 0 10px; 
      } 
      /*设置导航按钮*/ 
      #nav{ 
        /*开启绝对定位*/ 
        position: absolute; 
        /*定位*/ 
        bottom: 20px; 
        /* 
         * #outer 宽度 520px 
         *  
         * #nav 宽度 125px 
         *  
         * 520 - 125 = 395/2 = 197.5 
         */ 
        left: 197px; 
      } 
      #nav a{ 
        /*设置a浮动*/ 
        float: left; 
        /*设置宽和高*/ 
        width: 15px; 
        height: 15px; 
        /*设置背景颜色*/ 
        background-color: red; 
        /*设置外边距*/ 
        margin: 0 5px; 
        /*设置透明*/ 
        opacity: 0.5; 
        filter: alpha(opacity=50); 
      } 
    </style> 
  </head> 
  <body> 
    <!-- 
      Creare un div come contenitore 
    --> 
    <div id="outer"> 
      <!--Creare un ul per salvare le immagini--> 
      <ul id="imgList"> 
        <li><img src="img/1.jpg" /></li> 
        <li><img src="img/2.jpg" /></li> 
        <li><img src="img/3.jpg" /></li> 
        <li><img src="img/4.jpg" /></li> 
        <li><img src="img/5.jpg" /></li> 
      </ul> 
      <!--creare un div per alloggiare i pulsanti di navigazione--> 
      <div id="nav"> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
      </div> 
    </div> 
  </body> 
</html> 

2. Carousel logic:

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8"> 
    <title></title> 
    <style type="text/css"> 
      /*去除默认样式*/ 
      *{ 
        margin: 0; 
        padding: 0; 
      } 
      /*设置div*/ 
      #outer{ 
        width: 520px; 
        height: 333px; 
        /*设置居中*/ 
        margin: 50px auto; 
        /* 
         * 设置背景颜色 
         */ 
        background-color: greenyellow; 
        /*设置上下内边距*/ 
        padding: 10px 0; 
        /*为父元素开启相对定位*/ 
        position: relative; 
        /*隐藏溢出的内容*/ 
        overflow: hidden; 
      } 
      /*设置ul*/ 
      #imgList{ 
        /*去除项目符号*/ 
        list-style: none; 
        /*设置ul的宽度*/ 
        width: 2600px; 
        /*开启绝对定位*/ 
        position: absolute; 
        /* 
         * 通过修改ul的left值,可以切换图片 
         * 1 0px 
         * 2 -520px 
         * 3 -1040px 
         * 4 -1560px 
         * .... 
         */ 
        left: 0px; 
      } 
      /*设置li*/ 
      li{ 
        /*设置元素浮动*/ 
        float: left; 
        /*设置外边距*/ 
        margin: 0 10px; 
      } 
      /*设置导航按钮*/ 
      #nav{ 
        /*开启绝对定位*/ 
        position: absolute; 
        /*定位*/ 
        bottom: 20px; 
        /* 
         * #outer 宽度 520px 
         *  
         * #nav 宽度 125px 
         *  
         * 520 - 125 = 395/2 = 197.5 
         */ 
        left: 197px; 
      } 
      #nav a{ 
        /*设置a浮动*/ 
        float: left; 
        /*设置宽和高*/ 
        width: 15px; 
        height: 15px; 
        /*设置背景颜色*/ 
        background-color: red; 
        /*设置外边距*/ 
        margin: 0 5px; 
        /*设置透明*/ 
        opacity: 0.5; 
        filter: alpha(opacity=50); 
      } 
      #nav a:hover{ 
        background-color: black; 
      } 
    </style> 
    <script type="text/javascript" src="js/tools.js"></script> 
    <script type="text/javascript"> 
      window.onload = function(){ 
        //Ottieni l'ul con id 'imgList' 
        var imgList = document.getElementById("imgList"); 
        //Ottieni tutti i tag immagine 
        var imgs = document.getElementsByTagName("img"); 
        //Impostare la larghezza dell'ul 
        imgList.style.width = 520 * imgs.length + "px";  
        //Posizionare i pulsanti di navigazione al centro 
        //Ottieni il div con id 'outer' 
        var outer = document.getElementById("outer"); 
        //Ottieni il div con id 'nav' 
        var nav = document.getElementById("nav"); 
        nav.style.left = (outer.offsetWidth - nav.offsetWidth)/2 + "px"; 
        //Creare una variabile per salvare l'indice dell'immagine attualmente visualizzata 
        var index = 0; 
        //Ottieni tutti gli hyperlink 
        var links = document.getElementsByTagName("a"); 
        //Impostare l'hyperlink corrispondente come selezionato 
        links[index].style.backgroundColor = "black"; 
        //Accendere la transizione automatica delle immagini 
        autoChange(); 
        /* 
         * Passare all'immagine corrispondente cliccando sull'hyperlink 
         * Cliccando sul primo hyperlink, passare alla prima immagine 
         * Cliccando sul secondo hyperlink, passare alla seconda immagine 
         */ 
        //Associare una funzione di risposta al click a tutti gli hyperlink 
        for(var i=0 ; i<links.length ; i++){ 
          //Aggiungere un attributo all'hyperlink 
          links[i].num = i; 
          links[i].onclick = function(){ 
            //Quando si cambia l'immagine, per evitare l'influenza della transizione automatica, è necessario chiuderla 
            clearInterval(autoTimer); 
            //Ottieni l'indice dell'hyperlink cliccato corrente 
            //Aggiornare l'indice dell'immagine corrente 
            index = this.num; 
            //Passare all'immagine corrispondente 
            /* 
             * Passare all'immagine successiva, è necessario modificare il valore dell'attributo left di imgList 
             * 0 0*-520 
             * 1 1*-520 
             * 4 4*-520 
             */ 
            //imgList.style.left = -520*index + "px"; 
            //Impostare l'effetto di transizione 
            move(imgList , "left" , -520*index , 20 , function(){ 
              //Completamento del cambio delle immagini, attivare il cambio automatico 
              autoChange(); 
            }); 
            setA(); 
          }; 
        } 
        //Definire una variabile per salvare il timer di cambio automatico delle immagini 
        var autoTimer;  
        /* 
         * Definire una funzione per gestire il cambio automatico delle immagini 
         */ 
        function autoChange(){ 
          //Accendere un timer per gestire il cambio delle immagini 
          autoTimer = setInterval(function(){ 
            //Incremento dell'indice 
            index++; 
            //Verificare se l'indice è legittimo 
            index = index % imgs.length; 
            //Cambio delle immagini 
            move(imgList , "left" , -520*index , 20 , function(){ 
              //Completamento dell'animazione, cambio dei punti di navigazione 
              setA(); 
            }); 
          },3000); 
        } 
        /* 
         * La funzione è dedicata a impostare lo stato di selezione dei link 
         */ 
        function setA(){ 
          /* 
           * Poiché l'ultima immagine e la prima sono le stesse, quando l'immagine visualizzata è l'ultima, il primo link dovrebbe cambiare colore 
           */ 
          if(index >= imgs.length - 1){ 
            index = 0; 
            //Passare immediatamente all'immagine iniziale dopo aver raggiunto l'ultima immagine 
            imgList.style.left = 0; 
          } 
          /*Eseguire il ciclo sugli elementi link*/ 
          for(var i=0 ; i<links.length ; i++){ 
            //Impostare il colore di sfondo di tutti i link su rosso 
            links[i].style.backgroundColor = ""; 
          } 
          //Impostare il colore di sfondo del link selezionato su nero 
          links[index].style.backgroundColor = "black"; 
        } 
      }; 
    </script> 
  </head> 
  <body> 
    <!-- 
      Creare un div come contenitore 
    --> 
    <div id="outer"> 
      <!--Creare un ul per salvare le immagini--> 
      <ul id="imgList"> 
        <li><img src="img/1.jpg" /></li> 
        <li><img src="img/2.jpg" /></li> 
        <li><img src="img/3.jpg" /></li> 
        <li><img src="img/4.jpg" /></li> 
        <li><img src="img/5.jpg" /></li> 
        <li><img src="img/1.jpg" /></li> 
      </ul> 
      <!--creare un div per alloggiare i pulsanti di navigazione--> 
      <div id="nav"> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
        <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"></a> 
      </div> 
    </div> 
  </body> 
</html>

codice js esterno:

/* 
 *definire una funzione move() per eseguire effetti animazione semplici 
 * Parametro: 
 *obj oggetto su cui eseguire l'animazione 
 *attr attributo da modificare durante l'animazione 
 *target posizione di destinazione dell'animazione 
 *speed velocità di esecuzione dell'animazione 
 *callback funzione di callback, quando l'animazione è completata, questa funzione di callback verrà eseguita 
 */ 
function move(obj, attr, target, speed, callback) { 
  //chiudere il timer precedente 
  /* 
   *Di solito si salverà l'indicatore del timer come attributo dell'oggetto che esegue l'animazione, in modo da garantire che solo l'oggetto corrente possa accedere al timer 
   */ 
  clearInterval(obj.timer); 
  //giudicare se muoversi a sinistra o a destra 
  //0 --> 800, muoversi a destra 
  //se la posizione iniziale è minore della posizione di destinazione, muoversi a destra, con velocità positiva 
  //800 --> 0, muoversi a sinistra 
  //se la posizione iniziale è maggiore della posizione di destinazione, muoversi a sinistra, con velocità negativa 
  //ottenere la posizione iniziale dell'elemento 
  var current = parseInt(getStyle(obj, attr)); 
  if(current > target) { 
    //se la posizione iniziale è maggiore della posizione di destinazione, muoversi a sinistra, con velocità negativa 
    speed = -speed; 
  } 
  //accendere un timer per controllare il movimento di box1 
  obj.timer = setInterval(function() { 
    //ottenere il valore corrente di left di box1 
    var oldValue = parseInt(getStyle(obj, attr)); 
    //calcolare il nuovo valore tramite il valore precedente 
    var newValue = oldValue + speed; 
    //giudicare se newValue è maggiore di 800 
    /* 
     * Se l'animazione eseguita da 0 a 800, il valore diventa sempre più grande 
     * Se l'animazione eseguita da 800 a 0, il valore diventa sempre più piccolo 
     */ 
    if((speed > 0 && newValue > target) || (speed < 0 && newValue < target)) { 
      newValue = target; 
    } 
    //Modifica il valore di left di box1 al nuovo valore 
    obj.style[attr] = newValue + "px"; 
    //Quando box1 si sposta alla posizione 800px, fermare il movimento 
    if(newValue == target) { 
      clearInterval(obj.timer); 
      //Chiamare la funzione di callback 
      callback && callback(); 
    } 
  }, 30); 
} 
/* 
 * Utilizzato per ottenere lo stile corrente di qualsiasi elemento 
 * Parametro: 
 *   obj è l'elemento da ottenere lo stile 
 *   name è il nome dello stile da ottenere 
 * 
 * Quando si legge lo stile dell'elemento, se l'elemento non ha impostato lo stile, 
 * I browser come Firefox, Chrome calcolano automaticamente il valore di stile dell'elemento 
 * Per IE browser, a volte non calcola automaticamente ma restituisce il valore predefinito, ad esempio la larghezza viene restituita come auto 
 *    
 */ 
function getStyle(obj, name) { 
  //Verifica se il browser contiene il metodo getComputedStyle 
  if(window.getComputedStyle) { 
    //Supporta i browser normali 
    return getComputedStyle(obj, null)[name]; 
  } 
    //Supporta solo IE 
    return obj.currentStyle[name]; 
  } 
} 
/* 
 * Definisce una funzione speciale per aggiungere class agli elementi 
 * Parametro: 
 *   obj è l'oggetto con l'attributo class da aggiungere 
 *   cn è il valore dell'attributo class da aggiungere 
 */ 
function addClass(obj, cn) { 
  //Se l'elemento ha questa class non viene aggiunta, viene aggiunta solo se non c'è 
  if(!hasClass(obj, cn)) { 
    obj.className += " " + cn; 
  } 
} 
/* 
 * Crea una funzione per controllare se un elemento contiene la class specificata 
 * Se esiste, restituisce true. Altrimenti restituisce false 
 */ 
function hasClass(obj, cn) { 
  //Create a regular expression 
  var reg = new RegExp("\\b" + cn + "\\b"); 
  //Restituisce il risultato di controllo 
  return reg.test(obj.className); 
} 
/* 
 * Method used to remove the class value from the specified element 
 */ 
function removeClass(obj, cn) { 
  //To delete a class, replace this class with an empty string 
  //Create a regular expression 
  var reg = new RegExp("\\b" + cn + "\\b", "g"); 
  //Determine if obj contains this class 
  if(reg.test(obj.className)) { 
    //Replace the content with an empty string 
    obj.className = obj.className.replace(reg, ""); 
  } 
} 
/* 
 * Method used to switch the element's class 
 * If the element contains the class, delete it 
 * If the element does not contain the class, add it 
 * 
 */ 
function toggleClass(obj, cn) { 
  //Check if obj contains cn 
  if(hasClass(obj, cn)) { 
    //If there is such a class, delete it 
    removeClass(obj, cn); 
  } 
    //If there is no such class, add it 
    addClass(obj, cn); 
  } 
} 

Note:Find the pictures yourself

That's all for this article, I hope it will be helpful to everyone's learning, and I also hope everyone will support and cheer for the tutorial.

Declaration: The content of this article is from the network, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, nor assumes relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (when sending an email, please replace # with @) for reporting, and provide relevant evidence. Once confirmed, this site will immediately delete the suspected infringing content.

Ti potrebbe interessare