动画 Javascript OnMouseOver

Animation Javascript OnMouseOver

var positioner = 0;
var ames = setInterval(animate, 200);

function animate() {
    if(positioner <= 1000){
        document.getElementsByTagName('img')[0].style.backgroundPosition='-'+positioner+'px';
        positioner += 256;
    } else {
        document.getElementsByTagName('img')[0].style.backgroundPosition='-'+positioner+'px';
        positioner = 0;
    }
}
img { 
    background-image: url('https://cdn-images-1.medium.com/max/1600/1*WhDjw8GiV5o0flBXM4LXEw.png');
    background-repeat: no-repeat;
}
<img width="256px" height="256px" onmouseover="animate()"/>

那是我的代码,目前它正在自动移动,我想让它自动移动 onMouseOver!在我看来,如果 setInterval 可以放在那个 animate() 函数里面,那么这个问题就解决了,但是如何把 setInterval 放在函数里面呢??

给你,最好的方法是将 mouseOvermouseOut 作为侦听器处理,并将 setInterval 存储在一个变量中,以便稍后清除它。

var positioner = 0;
var ames;
var img = document.getElementsByTagName('img');

img[0].addEventListener('mouseover', () => {
    ames = setInterval(animate, 200);
});

img[0].addEventListener('mouseout', () => {
    if (ames)
        window.clearInterval(ames);
});

function animate() {
    if (positioner <= 1000) {
        img[0].style.backgroundPosition='-'+positioner+'px';
        positioner += 256;
    } else {
        img[0].style.backgroundPosition='-'+positioner+'px';
        positioner=0;
    }
}
img { 
    background-image: url('https://cdn-images-1.medium.com/max/1600/1*WhDjw8GiV5o0flBXM4LXEw.png');
    background-repeat: no-repeat;
}
<img width="256px" height="256px"/>

首先,animate()是一个Element的内置函数。如果将鼠标悬停在控制台上,您会收到一些错误消息。

Mauricio Sipmann 的回答有效,但他没有回答你的问题,'In my opinion, if the setInterval can be put inside that animate() function then this problem will be solved but how to put setInterval inside function??'。

这就是为什么我给出另一个解决方案。我的回答是肯定的。但是让我们先将 animate() 重命名为 myAnimate()。

  1. <img width="256px" height="256px" onmouseover="animate()"/>更改为<img width="256px" height="256px" onmouseover="myAnimate()"/>

  2. 将 setInterval() 移动到 myAnimate() 中,但保留变量声明 outside.i.e.

var positioner = 0;
var ames;

function myAnimate() {
    if (!ames) {
        ames = setInterval(myAnimate, 200);
    }
    if (positioner <= 1000) {
        document.getElementsByTagName('img')[0].style.backgroundPosition = '-' + positioner + 'px';
        positioner += 256;
    } else {
        document.getElementsByTagName('img')[0].style.backgroundPosition = '-' + positioner + 'px';
        positioner = 0;
    }
}

希望对您有所帮助