How to hook into the page wide click event?

2019-02-25 22:11发布

问题:

Just like the question states. I want to fire off an event that calls a method everytime the user clicks on the web page.

How do I do that without use of jQuery?

回答1:

Without using jQuery, I think you could do it like this:

if (document.addEventListener) {
    document.addEventListener('click',
        function (event) {
            // handle event here
        },
        false
    );
} else if (document.attachEvent) {
    document.attachEvent('onclick',
        function (event) {
            // handle event here
        }
    );
}


回答2:

Here's one way to do it..

if (window.addEventListener)
{    
    window.addEventListener('click', function (evt)
    {
        //do something
    }, false);
} 
else if(window.attachEvent)
{
    window.attachEvent('onclick', function (evt)
    {
        // do something (for IE)
    });
}


回答3:

$(document).click(function(){});


回答4:

document.onclick = function() { alert("hello"); };

note that this will only allow for one such function though.