图片翻转的类 利用oo模式编写

enix2212 2010-04-25
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<script type="text/javascript">
var addEvent=function(elem, evType, fn, capture){
    if (elem.addEventListener) {
        elem.addEventListener(evType, fn, capture);
    }
    else if (elem.attachEvent) {
        elem.attachEvent('on' + evType, fn);
    }
    else {
        elem['on' + evType] = fn;
    }
}
//事件监听方法
var Hover=function(config){
    this.config=config;
    this.init();
}
//定义一个hover类
Hover.prototype={
    init:function(){
        var that=this;
        var img=new Image();
        img.src=this.config.overSrc;
        this.config.o.setAttribute('src',this.config.outSrc);
        addEvent(that.config.o,'mouseover',function (e){that.toggle.call(this,e,that);},false);
        addEvent(that.config.o,'mouseout',function (e){that.toggle.call(this,e,that);},false);
    },
    toggle:function (e,b){
        var e=window.event || e;
        var target=e.srcElement || e.target;
        var src=e.type=='mouseover'?b.config.overSrc:b.config.outSrc;
        target.setAttribute('src',src);
    }
}
//hover 原型上添加两个方法 init和toggle    
window.onload=function(){
    new Hover({
        o:document.getElementsByTagName('img')[0],
        overSrc:'http://img2.cache.netease.com/cnews/2010/4/24/20100424103018d5b6c.jpg',
        outSrc:'http://img4.cache.netease.com/sports/2010/4/22/20100422180328a0d96.jpg'
    });   
   new Hover({
        o:document.getElementById('abc'),
        overSrc:'http://img1.cache.netease.com/cnews/2010/4/24/201004241001533d3c2.jpg',
        outSrc:'http://img1.cache.netease.com/cnews/2010/4/24/2010042410543717e94.jpg'
    });
}
//创建两个对象实例
</script>
<img /><br /><img id='abc' />
</body>
</html>
Global site tag (gtag.js) - Google Analytics