【发布时间】:2026-01-26 13:10:02
【问题描述】:
我想在鼠标悬停时给每一根头发一个弹跳动画。动画部分是在第一根头发上完成的,但我不想给每一个头发图像都赋予事件。 所以这是我的问题,我在我的 javascript 代码中使用构造函数。我是否可以在我的原型中创建一个方法并创建它的实例?所以基本上 我不想触发 10 个事件或 10 个 addEventListeners,我想要一个聪明的方法来解决这个问题。 我如何完成我的任务,因为每根头发都应该只在鼠标悬停时反弹
我的代码: HTML:
<div class="main">
<div class="hair">
<img src="images/single.png" id="hair1" width="13" height="40" >
<img src="images/single.png" id="hair2" width="13" height="40">
<img src="images/single.png" id="hair3" width="13" height="40">
<img src="images/single.png" id="hair4" width="13" height="40">
<img src="images/single.png" id="hair5" width="13" height="40">
<img src="images/single.png" id="hair6" width="13" height="40">
<img src="images/single.png" id="hair7" width="13" height="40">
<img src="images/single.png" id="hair8" width="13" height="40">
<img src="images/single.png" id="hair9" width="13" height="40">
</div>
<div class="face">
<img src="images/ec_logo.png">
</div>
Javascript:
(function(){
hair=function (){
return this;
};
hair.prototype={
bounce:function(){
//code for some bounce animation
}
};
})();
document.getElementById('hair??').addEventListener("mouseover",???,false);????????//this is the part i am confused about,how to give same animation to every single hair by using object instances???
【问题讨论】:
-
尝试使用jquery animate
-
我 don
t have a problem with animation,thats 很好...我只是想问如何为相同的动作调用每根头发,比如当我的鼠标悬停在 2 号头发上时,只有第 2 根头发应该弹跳跨度> -
给每根头发一个通用类,将鼠标悬停事件处理程序附加到该类。在事件处理程序中,使用 $(this).id 并使用该 id 进行动画处理
-
所以在我的 html 中,我必须为每根头发执行此 mouseover=function_bounce(this.id) ???或者我必须为每根头发编写 addEventListener 10 次???
-
如果您不想要 10 个不同的事件侦听器(这不会那么糟糕,顺便说一句),那么您将不得不使用 事件委托(搜索它)。请注意,这与构造函数或原型继承绝对无关。
标签: javascript event-delegation dom-events