好!欢迎访问迷津渡口 现在时间是: 天气 °C ~ °C

迷津渡口

越感到迷惑 越接近真理

javascript兼容性添加清除滚轮事件

前端难

                     ——小指夜哭

一入前端无底洞,从此身体被掏空。

工具架构不相通,样式脚本难兼容。

前端难,前端难,多歧路,脑仁痛。

安得世间本如法,堪破迷蒙见霓虹。


什么鬼?看Javascript滚轮事件就知道了,各种兼容性直接把你上个月吃的的隔夜饭都恶心吐了~

普通事件对象传递

浏览器IE6/7/8FFIE9/Opera/Safari/Chrome
传递方法

支持通过window.event获取事件对象。attachEvent方式添加事件时也支持通过事件对象作为绑定函数的第一个参数传入

任何时候只支持事件对象作为绑定函数第一个参数传入任何时候同时支持两种方式

普通事件采用方法绑定和解绑方法

绑定时,推荐绑定普通函数,不要绑定匿名函数,否则无法解绑;

IE中绑定事件this为window,事件有on前缀,同一个事件绑定的多个函数,后绑定的先执行;

其余浏览器this为绑定对象,事件不需要on前缀,同一个事件绑定的多个函数,按绑定顺序执行;

addEventListener中userCapture参数默认为false,表示在冒泡阶段绑定函数,true表示在捕获阶段绑定函数。

浏览器IEChromeFF

事件绑定方法

element.attachEvent(event, function)

element.addEventListener(event, function, useCapture)

element.addEventListener(event, function, useCapture)
事件解绑方法element.detachEvent(event, function)element.removeEventListener(event, function, useCapture)element.removeEventListener(event, function, useCapture)

滚轮事件

浏览器IEChromeFF
滚动事件

mousewheel(普通事件)

mousewheel(普通事件)DOMMouseScroll(DOM事件,只能通过事件绑定方法绑定事件)
滚动事件参数属性wheelDeltawheelDelta
detail
参数属性和上下关系,滚轮滚一格出现一个相应的数

向上滚:120

向下滚:-120

向上滚:120

向下滚:-120

向上滚:-3

向下滚:3

哭了吗,看下去吧,好东西在下面哦~

滚轮事件获取兼容实现方法

以下例子兼容实现了

添加绑定事件和清除绑定事件的方法:

事件函数可为匿名函数,尝试在相同事件绑定相同函数将直接忽略,自动阻止了事件默认行为和事件冒泡。

添加绑定滚轮事件和清除绑定滚轮事件:

将向下事件函数和向上事件函数分离,利用兼容函数将其再次合并。

个人认为多个向上向下滚轮事件函数没必要,因此本例仅实现了绑定单一向上向下函数,若需要可自行添加。

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>迷津渡口-javascript兼容性添加清除滚轮事件分享</title>
    <script>
    window.onload = function() {
        // 获取DOM对象
        var oBtn1=document.getElementById('btn1');
        var oBtn2=document.getElementById('btn2');
        var oDiv = document.getElementById('div1');
        
        // 点击oBtn1绑定oDiv的滚轮事件
        addEvent(oBtn1,'click',function(){addMouseWheel(oDiv, fnDown, fnUp);});
        // 点击oBtn2清除oDiv的滚轮事件
        addEvent(oBtn2,'click',function(){removeMouseWheel(oDiv);});
    };

    // 兼容性添加事件
    function addEvent(obj, sEvent, fn) {
        // 如果事件函数未被绑定过
        if (!obj['b' + sEvent + fn]) {
            // 利用独一无二的属性名保存绑定的函数
            // 同时利用call解决this问题,解决event兼容性,组织默认事件行为和事件冒泡
            obj['e' + sEvent + fn] = function(evt) {fn.call(obj,evt);if (evt.preventDefault) evt.preventDefault();if (evt.stopPropagation) evt.stopPropagation();return false;};
            if (obj.attachEvent) {
                obj.attachEvent('on' + sEvent, obj['e' + sEvent + fn]);
            } else {
                obj.addEventListener(sEvent, obj['e' + sEvent + fn], false);
            }
            obj['b' + sEvent + fn] = true;
        }
    }

    // 兼容性清除事件
    function removeEvent(obj, sEvent, fn) {
        if (obj['b' + sEvent + fn]) {
            if (obj.detachEvent) {
                obj.detachEvent('on' + sEvent, obj['e' + sEvent + fn]);
            } else {
                obj.removeEventListener(sEvent, obj['e' + sEvent + fn], false);
            }
            delete(obj['b' + sEvent + fn]);
            delete(obj['e' + sEvent + fn]);
        }
    }

    // 兼容性添加滚轮事件
    // 为方便将向上事件函数和向下事件函数分开传递
    // 个人认为没必要多个,因此没做多个,有需要也可以自行添加
    function addMouseWheel(obj, fnDown, fnUp) {
        // 获取向下和向上滚动的次数,易知相减就是滚动的总数
        obj.scrollDownNum=0;
        obj.scrollUpNum=0;
        // 将向下事件和向上事件合并绑定到滚轮事件里
        // 利用call保证this的一致性,传递evt保证事件兼容性
        obj.mousewheelfunction = function(evt) {
            if (isMouseWheelDown(evt)) {
                fnDown.call(obj,evt);
            } else {
                fnUp.call(obj,evt);
            }
        };
        addEvent(obj, 'mousewheel', obj.mousewheelfunction);
        addEvent(obj, 'DOMMouseScroll', obj.mousewheelfunction);
    }

    // 兼容性清除滚轮事件
    // 这里仅仅需清除一个属性函数,没必要传其他参数
    function removeMouseWheel(obj) {
        if (obj.mousewheelfunction) {
            removeEvent(obj, 'mousewheel', obj.mousewheelfunction);
            removeEvent(obj, 'DOMMouseScroll', obj.mousewheelfunction);
            delete(obj.mousewheelfunction);
        }
    }

    // 判断滚轮是否向下滚动一格
    function isMouseWheelDown(evt) {
        return evt.wheelDelta ? evt.wheelDelta < 0 : evt.detail > 0;
    }

    // 每向下滚动一格,执行一次本函数
    function fnDown(evt) {
        console.log('向下滚动事件的目标ID为:'+evt.target.id+',向下滚动次数为:'+ ++this.scrollDownNum);
        if (parseInt(this.style.height) < 1800)this.style.height=parseInt(this.style.height)+10+'px';
    }

    // 每向上滚动一格,执行一次本函数
    function fnUp(evt) {
        console.log('\t向上滚动事件的目标ID为:'+evt.target.id+',向上滚动次数为:'+ ++this.scrollUpNum);
        if (parseInt(this.style.height) > 50)this.style.height=parseInt(this.style.height)-10+'px';
    }
    </script>
</head>

<body style="height:2000px;">
   <button id="btn1">绑定滚轮事件</button><button id="btn2">清除滚轮事件</button>
    <div id='div1' style="margin-top:20px;width:200px;height:200px;background:red;"></div>
</body>

</html>

小指才疏学浅,有任何疏漏之处,欢迎不吝赐教~


点赞3
   支持一下
挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
 点赞
 签到
 表情
 图片
 代码
提交评论

清空信息
关闭评论
pearsonchool
 pearsonchool 约 8 小时前回复
#76
<a href="http://www.mwartsdrama.com/nike-roshe-run-floral-red-black-shoesh">nike roshe run floral red black</a> <a href="http://www.meshmotors.com/air-jordan-retro-31-cielo-azul-negro-zapatosp">air jordan retro 31 cielo azul negro</a> <a href="http://www.aspenmedisys.com/air-huarache-verde-abyss-zapatosk">air huarache verde abyss</a> <a href="http://www.smartiesland.com/mens-north-face-ski-jacket-clearance-northfaceh">mens north face ski jacket clearance</a> <a href="http://www.emcetolerie.com/dam%C3%A4nner-asics-gel-kinsei-5-minzgr%C3%BCn-schuhej">dam盲nner asics gel kinsei 5 minzgr眉n</a> <a href="http://www.lapaktoko.com/nike-kobe-11-guld-r%C3%B8d-skoh">nike kobe 11 guld r酶d</a>
pearsonchool http://www.pearsonchool.com/
lapaktoko
 lapaktoko 2019-02-14 09:01回复
#75
<a href="http://www.tmzred.com/kvinders-nike-kyrie-2-hvid-s%C3%B8lv-skoi">kvinders nike kyrie 2 hvid s酶lv</a> <a href="http://www.alcovozov.com/femminile-nike-kd-8-rosso-gituttio-scarpeq">femminile nike kd 8 rosso gituttio</a> <a href="http://www.ahmztradefx.com/womens-asics-gel-noosa-tri-10-green-silver-shoesj">womens asics gel noosa tri 10 green silver</a> <a href="http://www.isampled.com/2018-kors-white-totes-jet-set-scarf-large-mkh">2018 kors white totes jet set scarf large</a> <a href="http://www.aldervets.com/nike-lunar-force-1-svart-oransje-obuvi">nike lunar force 1 svart oransje</a> <a href="http://www.vanltl.com/nike-kd-9-grigio-oro-scarpej">nike kd 9 grigio oro</a>
lapaktoko http://www.lapaktoko.com/
cphwph
 cphwph 2019-02-12 11:52回复
#74
<a href="http://www.daunchbeauty.com/adidas-laufschuh-zx-flux-8k-collegiate-marina-militare-nero-bianca-schuheb">adidas laufschuh zx flux 8k collegiate marina militare nero bianca</a> <a href="http://www.farenyuk.com/nike-kobe-11-flyknit-nero-blu-butye">nike kobe 11 flyknit nero blu</a> <a href="http://www.howellsolar.com/air-jordan-11-bl%C3%A5-velvet-note-butye">air jordan 11 bl氓 velvet note</a> <a href="http://www.immoetvous.com/nike-air-jordan-eclipse-wolf-grigio-elephant-journey-obuve">nike air jordan eclipse wolf grigio elephant journey</a> <a href="http://www.janetsher.com/nike-kyrie-3-weave-grau-wei%C3%9F-obuvd">nike kyrie 3 weave grau wei脽</a> <a href="http://www.johngerretsen.com/tout-blanc-jordan-11-columbia-kurpesf">tout blanc jordan 11 columbia</a>
cphwph http://www.cphwph.com/
bandbwhitby
 bandbwhitby 2019-02-12 10:11回复
#73
<a href="http://www.hobbyfreaks.com/jordan-retro-6-varsity-r%C3%B8d-sort-obuve">jordan retro 6 varsity r酶d sort</a> <a href="http://www.inselwasser.com/salomon-s-lab-fellcross-2-noir-ink-scarpec">salomon s lab fellcross 2 noir ink</a> <a href="http://www.naturalcitral.com/nike-air-zoom-total-90-iii-wei%C3%9F-rot-fg-ny-kurpesb">nike air zoom total 90 iii wei脽 rot fg ny</a> <a href="http://www.sterneanswers.com/adidas-penguins-59-jake-guentzel-black-19172017-100th-anniversary-stitched-nhl-jersey-nflr">adidas penguins 59 jake guentzel black 19172017 100th anniversary stitched nhl jersey</a> <a href="http://www.agrilover.com/nike-internationalist-schwarz-wei%C3%9F-butyg">nike internationalist schwarz wei脽</a> <a href="http://www.alikexue.com/nike-womens-jim-plunkett-limited-camo-jersey-oakland-raiders-nfl-16-rush-realtree-nflz">nike womens jim plunkett limited camo jersey oakland raiders nfl 16 rush realtree</a>
bandbwhitby http://www.bandbwhitby.com/
thehogrider
 thehogrider 2019-02-10 07:21回复
#72
<a href="http://www.egyptmaritime.com/air-jordan-retro-3-gr%C3%B8n-lilla-skoh">air jordan retro 3 gr酶n lilla</a> <a href="http://www.erstube.com/air-jordan-retro-10-violet-royal-bleu-chaussuresh">air jordan retro 10 violet royal bleu</a> <a href="http://www.thecardplayer.com/illinois-fighting-illini-zephyr-ncaa-black--white-competitor-cap-hatl">illinois fighting illini zephyr ncaa black  white competitor cap</a> <a href="http://www.theweedaddict.com/adidas-zx-850-noir-rose-chaussuresh">adidas zx 850 noir rose</a> <a href="http://www.thecampingman.com/air-jordan-retro-29-negro-p%C3%BArpura-zapatosk">air jordan retro 29 negro p煤rpura</a> <a href="http://www.otuzbircek.com/air-jordan-retro-3-silver-blue-shoesi">air jordan retro 3 silver blue</a>
[url=http://www.thehogrider.com/]thehogrider[/url]
donggeomdo
 donggeomdo 2019-02-09 11:45回复
#71
<a href="http://www.daddeaze.com/nike-free-3.0-v4-blanc-tiffany-bleu-schuhea">nike free 3.0 v4 blanc tiffany bleu</a> <a href="http://www.debracousins.com/mennns-nike-shox-current-gul-oransje-scarpeb">mennns nike shox current gul oransje</a> <a href="http://www.yankaripark.com/womens-nike-huarache-utility-black-denmark-shoeso">womens nike huarache utility black denmark</a> <a href="http://www.yicailottery.com/jordan-retro-6-sort-infrar%C3%B8d-toddler-kurpesb">jordan retro 6 sort infrar酶d toddler</a> <a href="http://www.calebcraw.com/womens-new-balance-gym-clothes-zapatost">womens new balance gym clothes</a> <a href="http://www.liquidputter.com/girls-high-converse-shoesz">girls high converse</a>
donggeomdo http://www.donggeomdo.com/
hiltonskyshop
 hiltonskyshop 2019-02-08 15:28回复
#70
<a href="http://www.egyptmaritime.com/north-face-womens-gore-tex-jacket-purple-grey-northfaceh">north face womens gore tex jacket purple grey</a> <a href="http://www.erstube.com/air-jordan-retro-6-blau-himmelblau-schuheq">air jordan retro 6 blau himmelblau</a> <a href="http://www.thecardplayer.com/air-jordan-imminent-vert-chaussuresl">air jordan imminent vert</a> <a href="http://www.theweedaddict.com/mujeres-asics-gel-noosa-tri-7-negro-amarillo-zapatosq">mujeres asics gel noosa tri 7 negro amarillo</a> <a href="http://www.thecampingman.com/nike-air-max-lunar-1-himmelbl%C3%A5-guld-skoj">nike air max lunar 1 himmelbl氓 guld</a> <a href="http://www.otuzbircek.com/kvinners-nike-kyrie-2-r%C3%B8d-hvit-obuvi">kvinners nike kyrie 2 r酶d hvit</a>
hiltonskyshop http://www.hiltonskyshop.com/
trafassi
 trafassi 2019-02-06 17:30回复
#69
<a href="http://www.daunkatuk.com/authentic-air-max-1-for-vente-chaussuresa">authentic air max 1 for vente</a> <a href="http://www.fjernskjegget.com/asics-dam%C3%A4nner-gel-noosa-tri-8-violet-lila-multi-butya">asics dam盲nner gel noosa tri 8 violet lila multi</a> <a href="http://www.pharmacypartd.com/nike-free-3.0-blu-maschio-zero-obuvd">nike free 3.0 blu maschio zero</a> <a href="http://www.sobresazucar.com/air-jordan-eclipse-naranja-verde-scarpea">air jordan eclipse naranja verde</a> <a href="http://www.agivla.com/kd-trey-5-oransje-and-gr%C3%B8nn-make-scarpef">kd trey 5 oransje and gr酶nn make</a> <a href="http://www.avmbulten.com/nike-hyperrev-2015-vendita-qld-obuvd">nike hyperrev 2015 vendita qld</a>
trafassi http://www.trafassi.com/
aspenmedisys
 aspenmedisys 2019-02-06 10:08回复
#68
<a href="http://www.laketreepress.com/air-jordan-retro-10-nero-gray-scarpeh">air jordan retro 10 nero gray</a> <a href="http://www.prohaarklinik.com/nike-kyrie-1-rosso-bianca-scarpei">nike kyrie 1 rosso bianca</a> <a href="http://www.bonfanticare.com/adidas-stan-smith-himmelblau-orangen-schuheh">adidas stan smith himmelblau orangen</a> <a href="http://www.antoniopagni.com/nike-mercurial-superfly-ag-hyper-punch-gold-black-shoesq">nike mercurial superfly ag hyper punch gold black</a> <a href="http://www.wcshosting.com/julio-jones-platinum-jersey-nfli">julio jones platinum jersey</a> <a href="http://www.biddingstream.com/air-jordan-retro-13-kvinners-gr%C3%B8nn-gull-obuvp">air jordan retro 13 kvinners gr酶nn gull</a>
aspenmedisys http://www.aspenmedisys.com/
karmacanix
 karmacanix 2019-02-04 21:30回复
#67
<a href="http://www.tkbelazig.com/dam%C3%A4nner-air-jordan-retro-1-rot-grau-schuhei">dam盲nner air jordan retro 1 rot grau</a> <a href="http://www.swiftgrocer.com/nike-air-max-tailwind-5-dam%C3%A4nner-lila-schwarz-schuheh">nike air max tailwind 5 dam盲nner lila schwarz</a> <a href="http://www.warrnamboolag.com/nike-zoom-pegasus-33-gr%C3%B8nn-gr%C3%A5-obuvj">nike zoom pegasus 33 gr酶nn gr氓</a> <a href="http://www.paineesq.com/nike-zoom-structure-19-femminile-grigio-cielo-blu-scarpep">nike zoom structure 19 femminile grigio cielo blu</a> <a href="http://www.gemmatyndall.com/femmes-nike-cortez-rouge-blanc-chaussuresh">femmes nike cortez rouge blanc</a> <a href="http://www.cestreaming.com/prada-double-tote-bag-pradah">prada double tote bag</a>
karmacanix http://www.karmacanix.com/
顶部留言底部
 00:00/00:00
我想和你虚度时光 - 花房姑娘(9)
  1. 我想和你虚度时光
  2. 花房姑娘
  3. 恋恋风尘
  4. 我喜爱一切不彻底的事物
  5. 我的心里是满的
  6. Long Way
  7. 给少年的歌
  8. 晴日共剪窗
  9. 天上的月你的脸