添加暂停:"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>

试试这个。

在您的HTML文件中:

<div class="mySlides" onhover="myFunction" />

在您的JS文件中:

function myFunction() {
... do something
}

您可以在脚本中创建一个变量。在元素悬停时将其设置为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);
}

将超时id存储在一个变量中,并像一样在其上调用window.clearTimeout(...)

<script>
var myIndex = 0;
var timeout;
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";
timeout = setTimeout(carousel, 3000);

}


function stopCarousel() {
window.clearTimeout(timeout);
}
</script>

当然,您需要在您希望转盘停止的事件上调用stopCarousel-函数。

最新更新