Javascript:无法使用此自定义事件侦听器

时间:2016-06-14 12:01:57

标签: javascript

我正在尝试制作一个zoomIn和zoomOut事件监听器,但我似乎无法使它工作。有人能帮我吗?我的代码....

//Classes for my own personal custom event listeners

var customEvent1 = new CustomEvent(
    'custom1',
    {
        detail: 
        {
            zoomIn: false,
            zoomOut: false,
        },
        bubbles: true,
        cancelable: true
    }
);
document.dispatchEvent(customEvent1);

//Handlers for the custom events 

function custom1Handler(e)
{
    var windowHeight = window.innerHeight;
    var windowWidth = window.innerWidth;
    var height, width;
    height = windowHeight;
    width = windowWidth;
    if (height >= windowHeight || width >= windowWidth)
    {
        e.detail.zoomOut = true;
        console.log("Zoomed out");
    }
    else if (width <= windowWidth || width <= windowWidth)
    {
        e.detail.zoomIn = true;
        console.log("Zoomed in");
    }
    else 
    {
        console.log("Cant determine Custom Zoom Event Listener");
    }
}

//Initiate events  

document.addEventListener("custom1", custom1Handler, false);

它不会出错,但在放大页面或缩小时不会触发。我究竟做错了什么?

1 个答案:

答案 0 :(得分:0)

为其添加侦听器之后的Dispatch事件,而不是之前。

document.addEventListener("custom1", custom1Handler, false);
document.dispatchEvent(customEvent1);