2017-07-14 64 views
0

MDN告訴我如何創建一個自定義事件(我沒有得到很好)如何創建上下滾動的自定義事件?

var event = new Event('build'); 

// Listen for the event. 
elem.addEventListener('build', function (e) { ... }, false); 

// Dispatch the event. 
elem.dispatchEvent(event); 

,我知道如何檢測鼠標的滾動,以及...

var doScroll = function (e) { 
    // cross-browser wheel delta 
    e = window.event || e; 
    var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); 

    // Do something with `delta` 
    document.body.innerHTML = delta; 

    e.preventDefault(); 
}; 

if (window.addEventListener) { 
    window.addEventListener("mousewheel", doScroll, false); 
    window.addEventListener("DOMMouseScroll", doScroll, false); 
} else { 
    window.attachEvent("onmousewheel", doScroll); 
} 

但我不知道如何搭配這兩個相互並創建一個自定義事件,所以我可以有這樣的事情:

window.addEventListener('scrollUp', sUpFunction); 
window.addEventListener('scrollDown', sDownFunction); 

謝謝你們。

回答

2

首先我會用"wheel" event代替non-standardrized "mousewheel" event
我創建了一個scrollUp和scrollDown自定義事件分派的簡單實現。

編輯

我有一個添加了IE polyfill for the CustomEvent以支持IE以及

// For IE support 
 
(function() { 
 
    if (typeof window.CustomEvent === "function") return false; //If not IE 
 

 
    function CustomEvent (event, params) { 
 
    params = params || { bubbles: false, cancelable: false, detail: undefined }; 
 
    var evt = document.createEvent('CustomEvent'); 
 
    evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); 
 
    return evt; 
 
    } 
 

 
    CustomEvent.prototype = window.Event.prototype; 
 

 
    window.CustomEvent = CustomEvent; 
 
})(); 
 

 
let element = document.getElementsByClassName("scroll-area")[0], 
 
scrollUpEvent = new CustomEvent("scrollUp"), 
 
scrollDownEvent = new CustomEvent("scrollDown"); 
 

 
function scrollDown(){ 
 
    console.log("scrolled down"); 
 
} 
 
function scrollUP(){ 
 
    console.log("scrolled up"); 
 
} 
 

 
function scrollHappened(e){ 
 
    if(e.deltaY < 0){ 
 
    element.dispatchEvent(scrollUpEvent); 
 
    } else { 
 
    element.dispatchEvent(scrollDownEvent); 
 
    } 
 
} 
 
element.addEventListener("wheel", scrollHappened); 
 
element.addEventListener("scrollUp", scrollUP); 
 
element.addEventListener("scrollDown", scrollDown);
.scroll-area { 
 
    border: solid 2px black; 
 
    height: 30px; 
 
}
<div class="scroll-area">Scroll on me</div>

+0

真棒,但它不工作在IE ... –

+0

工作。謝謝。 –