javascript - 将 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>
解决方案
您可以在脚本中创建一个变量。在元素悬停时将其设置为 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);
}
推荐阅读
- c# - 如何使动态创建的按钮单击事件使用c#中数据库表的一行数据
- php - 集合为空,但是 if(!empty($tags)) 的计算结果为 true
- fortran - gfortran 在写语句的续行中添加空格
- c# - Span 和 Memory 作为方法签名中数组的替代品?
- web - Facebook Graph API – 从 Instagram 页面获取网站 – 截屏视频
- javascript - 禁用:'{readOnly}' ExtJs 是什么意思
- android - 无法解决 com.google.firebase:firebase-crash:17.0.2
- html - 如何从 cfquery 结果中选中复选框
- java - 调用命令出错!使用 Maven Cargo 将战争部署到 WebSphere Liberty 服务器时
- mysql - 更改选择列会使查询变慢