3

这是我的公司标志

我想在鼠标悬停时给每根头发一个反弹动画。动画部分是在第一根头发上完成的,但我不想给每一个头发图像都提供事件。所以这是我的问题,在我的 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???
4

2 回答 2

0
// one event listener for whole 'haircut'
document.getElementsByClassName('hair')[0].addEventListener('mouseover',
function(objEvent)
{
    var elImg = objEvent.target;
    if (elImg.nodeName == 'IMG')
    {
        objEvent.stopPropagation();
        console.log(elImg.getAttribute('id')); // just for debug
        // xxx.bounce(elImg) or whatever you want
    }
}, false);
于 2013-06-13T13:18:49.180 回答
0

您可以使用以下方法延迟反弹setTimeout

(function(){

    // "private" vars
    var delayPace = 100;// ms
    var instanceCount = 0;


    hair = function (){
        // don't need to return this if it's going 
        // to be instantiated via the new keyword
        this.delay = instanceCount * delayPace;
        instanceCount++;
    };


    hair.prototype={
        delay : 0,

        bounce : function(){
             this.stop();
             this._t = setTimeout(this._bounce, this.delay);
        },

        _bounce : function(){
            // this is were the actual magic happens
        },

        stop : function(){
            if(this.t){
                clearTimeout(this.t);
            }
            // other code to stop the animation
        }
    };
})();

// keep all your hairs in one place!
var hairs = [];

// instantiate them
hairs.push(new hair());
//...
hairs.push(new hair());

var onHover = function(){
    hairs.forEach(function(h){
        h.bounce();
    });
}
于 2013-06-13T14:28:47.777 回答