猿问

如何在 JavaScript 中停止鼠标悬停的间隔?

<script>

  var pics = [ 

  "image/city (1).jpg",

    "image/city (2).jpg", 

    "image/city (3).jpg", 

    "image/city (4).jpg",

    "image/city (5).jpg",

    "image/city (6).jpg",

    "image/city (7).jpg",

    "image/city (8).jpg",

    "image/beach.jpg",

    "image/beach2.jpg"

  ];

  

  var inval;

  var photo;


  function carousel() {

    photo = document.getElementById('carousel-pics'); 

    var i = -1;

    inval = setInterval(function() {

        i++;

        if (i >= pics.length) {

          i = 0;

        }

        photo.src = pics[i];

       }, 1000);   

      }      

      

      function removeInterval() {

        clearInterval(inval);

     }


  document.getElementById('carousel-pics').addEventListener("mouseover", removeInterval);

</script>


<div class="polaroid" id="carousel-div" style="width:1000px; height:600px;">

  <img id="carousel-pics" src="image/city (1).jpg" alt="athens" style="width:1000px; height:600px;">

 

</div>

上面的代码是一些照片的幻灯片放映。当我将鼠标悬停在照片上时,我想停止幻灯片放映。但这不起作用。如果我添加一个按钮来停止幻灯片放映,它可以工作,但是当我使用鼠标悬停事件时,它不起作用。



杨魅力
浏览 83回答 2
2回答

梵蒂冈之花

我在这里看到的一个问题是<img>标签低于script标签。当您尝试附加addEventListenerat时document.getElementById('carousel-pics'),它将不起作用,因为document.getElementById('carousel-pics')此时为空。尝试保持script在 html 以下。<script>&nbsp; let ele1 = document.getElementById("test")&nbsp; console.log('[1]' , ele1)</script><div id="test"></div><script>&nbsp; let ele2 = document.getElementById("test")&nbsp; console.log('[2]' , ele2)</script>上面是相同的代码表示。您可以在第一个脚本中看到该元素null,而在第二个脚本中则不是

三国纷争

如上所述,改变顺序。主体 div 先于脚本。改个图片名字就坏了下面给出了示例var pics = [&nbsp; "https://images.unsplash.com/photo-1555797487-a1f30b5d8d55?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=589&q=400",&nbsp; "https://images.unsplash.com/photo-1533158307587-828f0a76ef46?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1567&q=80",&nbsp; "https://images.unsplash.com/photo-1555797487-a1f30b5d8d55?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=589&q=400"];const photo = document.getElementById("carousel-pics");function carousel() {&nbsp; let index = -1;&nbsp; const inval = setInterval(function() {&nbsp; &nbsp; index++;&nbsp; &nbsp; if (index >= pics.length) (index = 0);&nbsp; &nbsp; photo.src = pics[index];&nbsp; }, 1000);&nbsp; return () => clearInterval(inval)}const unsubsriber = carousel()photo.addEventListener("mouseover", unsubsriber);<div class="polaroid" id="carousel-div" style="width:1000px; height:600px;">&nbsp; <img id="carousel-pics" src="https://images.unsplash.com/photo-1555797487-a1f30b5d8d55?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=589&q=400" alt="athens" style="width:1000px; height:600px;">&nbsp;</div>
随时随地看视频慕课网APP

相关分类

Html5
我要回答