【发布时间】:2021-03-24 10:33:54
【问题描述】:
如果有人可以提供帮助,那就太好了。我创建了一个动画菜单。唯一的问题是,在我的 JS 中,我为所有五个按钮重复了我的代码。我试图从每个 html 元素中获取 id,以优化我的脚本,但它不起作用。请帮忙。这是我的代码:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="html/js/jquery.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<script type="text/javascript" src="menu.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<nav>
<div class="button-container">
<a id="link-1" class="link" onclick="location='page1.html'; return false" href="http://Buttonname1">
<!-- Image apparaissant au clic -->
<img id="bottom-1-clicked" class="toggle-1" src="button58.gif">
<!-- Image apparaissant au survol après disparition de l'image d'origine -->
<img id="bottom-1" class="toggle-1" src="button59.gif">
<!-- Image apparaissant au chargement de la page. Glisse vers la droite au survol puiq revient vers la gauche -->
<img id="top-1" class="toggle-1" src="button55.gif">
<span class="text-container">Buttonname1</span>
</a>
</div>
<div class="button-container">
<a id="link-2" class="link" onclick="location='page2.html'; return false" href="http://Buttonname2">
<img id="bottom-2-clicked" class="toggle-2" src="button58.gif" alt="">
<img id="bottom-2" class="toggle-2" src="button59.gif" alt="">
<img id="top-2" class="toggle-2" src="button55.gif" alt="">
<span class="text-container">Buttonname2</span>
</a>
</div>
</nav>
</body>
</html>
这是我的 JS:
$(document).ready(function(){
setInterval(function() {
$('.link').hover(function(childs) {
// Hovering the menu item, the first image slides to the right, discovering another image
$(this.id).hover(function(){
$(":nth-child(3)", this).attr('id').stop(true, false).animate({ left: 130 }, 300);
});
// On mouse leave, the image slides back to the left
$(this.id).mouseleave(function(){
$(":nth-child(3)", this).attr('id').stop(true, false).animate({ left: 0 }, 300);
});
// On click, the image changes, displaying a third image
$(this.id).mousedown(function(){
$(":nth-child(2)", this).attr('id').hide(50);
$(":nth-child(1)", this).attr('id').show(50);
});
});
}, 300 );
});
【问题讨论】:
-
你应该用英文写你的cmets,这样更多的人会明白
-
您的代码似乎很混乱。每 300 毫秒,您将绑定另一个
hover事件处理程序,它本身还有 3 个其他事件处理程序,包括另一个hover处理程序。我不确定您的目标到底是什么,但我可以告诉您,现在的逻辑是不正确的,并且您获取元素的id的请求不相关,因为这不是代码的编写方式.您能否编辑问题以包含所有相关的 HTML 和 CSS 以及您的目标描述。 -
在 Rory 的 cmets 上扩展,使用
$(this.id)省略了 id 选择器所需的"#"前缀,等效于$('link-1'),它正在寻找元素<link-1></link-1>。你的代码充满了问题 -
使代码可在 sn-p 中运行。
标签: javascript jquery animation events jquery-animate