我似乎无法找到这个问题的答案,所以我想我会问。我正在编写我的第一个网站,当鼠标悬停在每个单独的导航元素上时,我正在使用一点点 Javascript 向上滑动它。然后在鼠标移出时它会向下滑动。
它工作正常,除非当鼠标在“向上”有时间向下滑动之前从“向上”元素变为“向下”元素时,它会变得混乱并保持向上,而“向下”元素认为它应该滑动向下。我认为新的鼠标悬停事件与前一个事件混淆了,但我不确定如何修复它。
我希望这能解释我的问题,这是我正在使用的代码(CSS 非常简单,位置对于每个导航选项卡都是相对的,所以我没有显示它):
Javascript:
var cartridges, obj, lastObj;
var velocity = 2;
function setUp() {
if (!document.getElementById) return;
cartridges = document.getElementsByClassName('navigation');
for (var i = 0; i < cartridges.length; i++) {
cartridges[i].onmouseover = slideUp;
cartridges[i].onmouseout = slideDown;
}
}
function slideUp(e) {
if (!e) var e = window.event;
obj = (e.target) ? e.target: e.srcElement;
var up = obj.style.top;
up = up.substring(0, up.length - 2);
parseInt(up);
function frame() {
up -= velocity; // update parameters
obj.style.top = up + "px"; // show frame
if (up <= -100) // check finish condition (negative because that pushes it up, otherwise it would go down
clearInterval(id);
}
var id = setInterval(frame, 10); // draw every 10ms
}
function slideDown() {
var up = obj.style.top;
up = up.substring(0, up.length - 2);
parseInt(up);
function frame() {
up++; // update parameters
obj.style.top = up + "px";
if (up >= 0) // check finish condition (negative because that pushes it up, otherwise it would go down
clearInterval(id);
}
var id = setInterval(frame, 10); // draw every 10ms
}
window.onload = setUp;
HTML:
<div id="navigation">
<ul>
<li><a class="navigation" href="index.html" ><img id="home" alt="Home" src="../images/cartridge_grey_index.png" /></a></li>
<li><a class="navigation" href="aboutme.html"><img id="aboutme" alt="About Me" src="../images/cartridge_grey_aboutme.png" /></a></li>
<li><a class="navigation" href="resume.html"><img id="resume" alt="resume" src="../images/cartridge_grey_resume.png" /></a></li>
<li><a class="navigation" href="projects.html"><img id="projects" alt="projects" src="../images/cartridge_grey_projects.png" /></a></li>
<li><a class="navigation" href="blog.html"><img id="blog" alt="blog" src="../images/cartridge_grey_blog.png" /></a></li>
<li><a class="navigation" href="contact.html"><img id="contact" alt="contact" src="../images/cartridge_grey_contact.png" /></a></li>
</ul>
</div>