好!欢迎访问迷津渡口 现在时间是: 天气 °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
   支持一下
挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
 点赞
 签到
 表情
 图片
 代码
提交评论

清空信息
关闭评论
soextfence
 soextfence 约 3 小时前回复
#158
<a href="http://www.dominiogold.com/m%C3%A4nner-nike-air-huarache-nm-light-grau-schuhej">m盲nner nike air huarache nm light grau</a> <a href="http://www.saaqlabaie.com/nike-roshe-run-frau-2015-flynit-orange-schwarz-wei%C3%9F-schuhei">nike roshe run frau 2015 flynit orange schwarz wei脽</a> <a href="http://www.acheidf.com/nike-flyknit-racer-svart-hvit-pris-obuvj">nike flyknit racer svart hvit pris</a> <a href="http://www.jrsmetalsinc.com/nero-and-teal-nike-air-max-scarpel">nero and teal nike air max</a> <a href="http://www.kumowindham.com/nike-mercurial-noir-orange-chaussuresh">nike mercurial noir orange</a> <a href="http://www.waybeyondeli.com/nike-flyknit-air-max-femminile-nero-argento-arancia-scarpeh">nike flyknit air max femminile nero argento arancia</a>
soextfence http://www.soextfence.com/
ayuinc
 ayuinc 2019-04-17 06:25回复
#157
<a href="http://www.theskifanatic.com/mennns-nike-roshe-run-high-r%C3%B8d-oransje-obuvl">mennns nike roshe run high r酶d oransje</a> <a href="http://www.bestoftumblr.com/air-jordan-retro-14-womens-grey-pink-shoesh">air jordan retro 14 womens grey pink</a> <a href="http://www.thehogrider.com/air-jordan-phase-argento-blu-scarpei">air jordan phase argento blu</a> <a href="http://www.artpreneure.com/dam%C3%A4nner-nike-air-max-tn-alle-blau-schuhej">dam盲nner nike air max tn alle blau</a> <a href="http://www.thefarmergirl.com/baltimore-orioles-new-era-2018-mlb-clubhouse-low-crown-59fifty-cap-hath">baltimore orioles new era 2018 mlb clubhouse low crown 59fifty cap</a> <a href="http://www.shetablink.com/nike-zoom-pegasus-31-vert-chaussuresh">nike zoom pegasus 31 vert</a>
ayuinc http://www.ayuinc.com/
cuttingedgeoffers
 cuttingedgeoffers 2019-04-17 06:04回复
#156
<a href="http://www.bradleykountryacres.net/air-jordan-1-svart-laser-butya">air jordan 1 svart laser</a> <a href="http://www.buyggmotors.net/asics-asics-gel-kayano-17-gr%C3%A5-lyser%C3%B8d-schuhed">asics asics gel kayano 17 gr氓 lyser酶d</a> <a href="http://www.calvaryneworleans.net/nike-sb-koston-max-gris-chaussuresd">nike sb koston max gris</a> <a href="http://www.calvarynola.net/kobe-10-elite-nero-and-bianca-kit-obuvf">kobe 10 elite nero and bianca kit</a> <a href="http://www.campaignribbons.net/nike-roshe-run-junior-azul-kurpese">nike roshe run junior azul</a> <a href="http://www.camxl.net/nike-lebron-13-bambini-viola-rosso-schuhed">nike lebron 13 bambini viola rosso</a>
cuttingedgeoffers http://www.cuttingedgeoffers.net/
tekmenu
 tekmenu 2019-04-16 20:31回复
#155
<a href="http://www.chocopictures.com/nike-air-flight-89-noir-suede-chaussuresj">nike air flight 89 noir suede</a> <a href="http://www.baluntan.com/adidas-gazelle-lila-gelb-schuhek">adidas gazelle lila gelb</a> <a href="http://www.anderonedream.com/new-york-giants-color-rush-jersey-landon-collins-nflh">new york giants color rush jersey landon collins</a> <a href="http://www.variaponsel.com/vibram-five-fingers-kvinners-sprint-rose-r%C3%B8d-gul-obuvi">vibram five fingers kvinners sprint rose r酶d gul</a> <a href="http://www.allmydibs.com/nike-flyknit-trainer-white-black-shoesj">nike flyknit trainer white black</a> <a href="http://www.macusaa.com/nike-zoom-clear-out-black-shoesl">nike zoom clear out black</a>
tekmenu http://www.tekmenu.com/
deshiresult
 deshiresult 2019-04-16 09:40回复
#154
<a href="http://www.hutchinsmedia.com/adidas-ultra-boost-rosso-blu-scarpej">adidas ultra boost rosso blu</a> <a href="http://www.datesfordate.com/nike-sb-stefan-janoski-max-cool-grigio-scarpei">nike sb stefan janoski max cool grigio</a> <a href="http://www.spchemtech.com/tcu-baseball-cap-hath">tcu baseball cap</a> <a href="http://www.eadamattia.com/femmes-air-jordan-retro-6-violet-chaussuresh">femmes air jordan retro 6 violet</a> <a href="http://www.citypixxel.com/nike-lab-air-max-2019-gris-noir-chaussuresj">nike lab air max 2019 gris noir</a> <a href="http://www.megasatinc.com/adidas-harden-vol-1-wei%C3%9F-wein-schuhek">adidas harden vol 1 wei脽 wein</a>
deshiresult http://www.deshiresult.com/
etxekalte
 etxekalte 2019-04-15 00:15回复
#153
<a href="http://www.soextfence.com/air-jordan-retro-28-blue-black-shoesk">air jordan retro 28 blue black</a> <a href="http://www.amemedgroup.com/nike-free-5.0-v2-kvinder-fluorescence-gr%C3%B8n-r%C3%B8d-sort-skoj">nike free 5.0 v2 kvinder fluorescence gr酶n r酶d sort</a> <a href="http://www.shawkreizer.com/dam%C3%A4nner-nike-flyknit-lila-schuheh">dam盲nner nike flyknit lila</a> <a href="http://www.powerwomanbc.com/men-nike-air-max-2011-grey-red-shoesk">men nike air max 2011 grey red</a> <a href="http://www.kilaswacana.com/black-and-gold-mk-belt-mkh">black and gold mk belt</a> <a href="http://www.hobartcomfest.com/menn-nike-air-max-tn-gr%C3%A5-gr%C3%B8nn-hvit-obuvi">menn nike air max tn gr氓 gr酶nn hvit</a>
etxekalte http://www.etxekalte.com/
mamapjblog
 mamapjblog 2019-04-14 20:22回复
#152
<a href="http://www.ortzproducts.com/new-york-knicks-47-nba-pink-tie-dye-47-clean-up-cap-hath">new york knicks 47 nba pink tie dye 47 clean up cap</a> <a href="http://www.cooterscamera.com/nike-shox-avenue-blanc-or-chaussuresh">nike shox avenue blanc or</a> <a href="http://www.marjalfun.com/nike-cortez-nylon-granite-blanc-chaussuresj">nike cortez nylon granite blanc</a> <a href="http://www.alecsblog.com/nike-air-max-tailwind-8-dam%C3%A4nner-gr%C3%BCn-schwarz-schuhej">nike air max tailwind 8 dam盲nner gr眉n schwarz</a> <a href="http://www.troudumonde.com/kvinders-air-jordan-retro-14-appelsin-gul-skok">kvinders air jordan retro 14 appelsin gul</a> <a href="http://www.smilesdrdavid.com/air-jordan-retro-2-rosa-gituttio-scarpeh">air jordan retro 2 rosa gituttio</a>
mamapjblog http://www.mamapjblog.com/
livinggreedy
 livinggreedy 2019-04-12 20:49回复
#151
<a href="http://www.teamdalarna.com/nike-zoom-clear-out-pink-blue-shoesj">nike zoom clear out pink blue</a> <a href="http://www.syairshamyoun.com/nike-air-force-1-mid-outdoor-gr%C3%B8n-skoi">nike air force 1 mid outdoor gr酶n</a> <a href="http://www.fizalisfresh.com/femminile-nike-blazer-rosso-blu-scarpel">femminile nike blazer rosso blu</a> <a href="http://www.fsscas.com/nike-air-force-1-all-red-low-shoesj">nike air force 1 all red low</a> <a href="http://www.imagimp.com/michael-kors-jet-set-pink-purse-mkh">michael kors jet set pink purse</a> <a href="http://www.burmamaritime.com/nike-free-tr-bl%C3%A5-rosa-obuvi">nike free tr bl氓 rosa</a>
livinggreedy http://www.livinggreedy.com/
abartz
 abartz 2019-04-11 22:08回复
#150
<a href="http://www.squigglecase.com/adidas-john-wall-2-rosa-hvit-chaussuresf">adidas john wall 2 rosa hvit</a> <a href="http://www.hshuixin.com/nike-free-rn-wei%C3%9F-and-schwarz-mirror-chaussuresa">nike free rn wei脽 and schwarz mirror</a> <a href="http://www.cnnturkcanli.com/zx-flux-blau-lightning-butya">zx flux blau lightning</a> <a href="http://www.milkybeer.com/adidas-zx-gr%C3%A5-gul-butyc">adidas zx gr氓 gul</a> <a href="http://www.adsohold.com/maschio-asics-gel-kinsei-5-oro-argento-scarpeg">maschio asics gel kinsei 5 oro argento</a> <a href="http://www.ashevillewigs.com/maschio-nike-flyknit-lunar-3-rosa-arancia-chaussuresc">maschio nike flyknit lunar 3 rosa arancia</a>
abartz http://www.abartz.com/
manglammovers
 manglammovers 2019-04-11 18:09回复
#149
<a href="http://www.bgaddiict.com/kvinders-nike-free-run-4.0-lyser%C3%B8d-gr%C3%A5-skok">kvinders nike free run 4.0 lyser酶d gr氓</a> <a href="http://www.deriogolf.com/nike-air-max-90-vapor-gr%C3%BCn-schuheh">nike air max 90 vapor gr眉n</a> <a href="http://www.poluscompany.com/nike-tanjun-red-mens-shoesk">nike tanjun red mens</a> <a href="http://www.pariswebjob.com/nike-flyknit-racer-volt-gr%C3%B8n-and-sort-skol">nike flyknit racer volt gr酶n and sort</a> <a href="http://www.dakvideo.com/kvinners-nike-free-run-2-oransje-obuvk">kvinners nike free run 2 oransje</a> <a href="http://www.freshkeema.com/adidas-ace-second-generation-15.1-fg-ag-verde-rosso-nero-scarpei">adidas ace second generation 15.1 fg ag verde rosso nero</a>
[url=http://www.manglammovers.com/]manglammovers[/url]
顶部留言底部
 00:00/00:00
我想和你虚度时光 - 花房姑娘(9)
  1. 我想和你虚度时光
  2. 花房姑娘
  3. 恋恋风尘
  4. 我喜爱一切不彻底的事物
  5. 我的心里是满的
  6. Long Way
  7. 给少年的歌
  8. 晴日共剪窗
  9. 天上的月你的脸