gpt4 book ai didi

javascript - 如何使图像在鼠标悬停时多次更改

转载 作者:行者123 更新时间:2023-12-02 13:45:21 25 4
gpt4 key购买 nike

我试图多次更改图像,因此我使用了 setInterval 但它不会停止

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<a href="https://www.google.com" target="_blank">
<img onmouseover="setInterval(mouseOver,500)" onmouseout="mouseOut()" id="a" src="1.jpg" style="height: 45vh; width: 23vw;">
</a>
<script>
function mouseOver()
{
element=document.getElementById("a")
if (element.src.match("pic_bulboff.jpg"))
{
document.getElementById("a").src="8.jpg";
}
else if (element.src.match("8.jpg"))
{
document.getElementById("a").src="6.jpg";
}
else
{
document.getElementById("a").src="1.jpg";
}
}
function mouseOut()
{
document.getElementById("a").src="1.jpg";
}
</script>
</body>
</html>

最佳答案

使用clearInterval并跟踪初始间隔:

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<a href="https://www.google.com" target="_blank">
<img onmouseover="init()" onmouseout="mouseOut()" id="a" src="http://placecage.com/400/400" style="height: 45vh; width: 23vw;">
</a>
<script>
var interval;

function init() {
interval = setInterval(mouseOver, 500)
}

function mouseOver() {
element = document.getElementById("a")
if (element.src.match("400/400")) {
document.getElementById("a").src = "http://placecage.com/300/300";
} else if (element.src.match("300/300")) {
document.getElementById("a").src = "http://placecage.com/200/200";
} else {
document.getElementById("a").src = "http://placecage.com/500/500";
}
}

function mouseOut() {
document.getElementById("a").src = "http://placecage.com/400/400";
clearInterval(interval)
}
</script>
</body>

</html>

关于javascript - 如何使图像在鼠标悬停时多次更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41444584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com