首页 > 解决方案 > 将 pause: "hover" 添加到现有 js

问题描述

新来的,所以请原谅任何错误。我已经搜索了 stackoverflow,但找不到将悬停暂停添加到我从 W3Schools 获得的现有脚本的方法,谁能告诉我怎么做?这是我正在使用的代码:

<script>
var myIndex = 0;
carousel();

function carousel() {
  var i;
  var x = document.getElementsByClassName("mySlides");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";  
  }
  myIndex++;
  if (myIndex > x.length) {myIndex = 1}    
  x[myIndex-1].style.display = "block";  
  setTimeout(carousel, 3000);

}
</script>

html

<!DOCTYPE html>
<html>

<head>
<title>flytipping</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="text/html; charset=iso-8859-2" http-equiv="Content-Type">
<link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>

<h2 class="w3-center">Flytipping_5</h2>

<div class="w3-content w3-section" style="max-width:70%">
  <img class="mySlides" src="1.JPG" style="width:100%" alt="">
  <img class="mySlides" src="2.JPG" style="width:100%" alt="">
  <img class="mySlides" src="3.JPG" style="width:100%" alt="">

</div>

<script>
var myIndex = 0;
carousel();

function carousel() {
  var i;
  var x = document.getElementsByClassName("mySlides");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";  
  }
  myIndex++;
  if (myIndex > x.length) {myIndex = 1}    
  x[myIndex-1].style.display = "block";  
  setTimeout(carousel, 3000);

}
</script>

</body>
</html>

标签: javascript

解决方案


您可以在脚本中创建一个变量。在元素悬停时将其设置为 true,并在您的函数中检查该变量是否为 true,然后不要移动您的图像。但是您必须在鼠标移出时取消设置此变量。

像这样的东西:

<div onmouseover="stopCarousel()" onmouseout="startCarousel()"></div>
var doCarousel = true;
function stopCarousel() {
  doCarousel=false;
}

function startCarousel() {
  doCarousel=true;
}

function carousel() {
  if(!doCarousel) return;

  var i;
  var x = document.getElementsByClassName("mySlides");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";  
  }
  myIndex++;
  if (myIndex > x.length) {myIndex = 1}    
  x[myIndex-1].style.display = "block";  
  setTimeout(carousel, 3000);

}

推荐阅读