gpt4 book ai didi

Javascript 鼠标悬停/鼠标移出动画按钮

转载 作者:行者123 更新时间:2023-11-30 06:54:28 24 4
gpt4 key购买 nike

我有一个按钮和 onmouseover 我希望它以 10 像素的速度向右移动 100ish 像素然后停止。移动不是问题,停止是问题。我可以用 jquery 做到这一点,但我需要学习如何在 javascript 中从头开始。到目前为止,这是我向右移动的脚本。

function rollRight() {      
imgThumb.style.left = parseInt (imgThumb.style.left) + 10 + 'px';
animate = setTimeout(rollRight,20);
}

它移动得很好所以为了停止它我尝试将循环量设为 5x10=50px 并再次将其写为

function rollRight() {
var i=0;
while (i < 5) {
imgThumb.style.left = parseInt (imgThumb.style.left) + 10 + 'px';
animate = setTimeout(rollRight,20);
i++;
};
}

现在,我想我遗漏了一段让它返回 while 函数的 [] 值的部分,但我不确定如何让它工作。一旦我有了移动权,我就可以应用相同的原则在鼠标移出时将其移回。

如果有人能帮我解决这个问题那就太好了。如果您有更好的脚本来制作仅使用 javascript 而没有库的动画,那也很棒。

编辑:因为将其保留为注释效果不佳,这是我当前的代码

function rollRight() {   
var left = parseInt (imgThumb.style.left);
if(left < 50) { // or any other value
imgThumb.style.left = left + 10 + 'px';
animate = setTimeout(rollRight,20);
}
}

function revert() {
var left = parseInt (imgThumb.style.left);
if(left < 50) { // or any other value
imgThumb.style.left = left + -10 + 'px';
animate = setTimeout(rollRight,20);
}
}

在还原过程中,我在让它向后移动时遇到了问题。它可能在 if(left<50) 部分。

最佳答案

var animate = null;

function rollRight() {
if(animate) clearTimeout(animate);
var left = parseInt (imgThumb.style.left);
if(left < 50) { // or any other value
imgThumb.style.left = left + 10 + 'px';
animate = setTimeout(rollRight,20);
}
}

function revert() {
if(animate) clearTimeout(animate);
var left = parseInt (imgThumb.style.left);
if(left > 0) {
imgThumb.style.left = (left - 10) + 'px';
animate = setTimeout(revert,20);
}
}

关于Javascript 鼠标悬停/鼠标移出动画按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13168440/

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