Is binding a click event to document better than binding it to body?

后端 未结 5 1979
逝去的感伤
逝去的感伤 2021-02-20 15:55

The question is simply between

$(\"body\").click(function(e){}); vs $(document).click(function(e){});

which is more efficient or advisa

相关标签:
5条回答
  • 2021-02-20 16:26

    If the page height is smaller than the viewport height, then clicking on the viewport below the page will not trigger the 'body' click handler, but only the document click handler.

    Live demo: http://jsfiddle.net/simevidas/ZVgDC/

    In the demo, try clicking on the area below the text, and you will see that only the document click handler executes.

    Therefore, it is better to bind the handler to the Document object.

    0 讨论(0)
  • 2021-02-20 16:26

    Also the body might not cover the whole visible window (some crazy styles cause that)! I don't know if you would still get the click event in this case. So better bind it to document.

    0 讨论(0)
  • 2021-02-20 16:29

    Binding it to document seems to be the standard practice, so I would stick with that.

    document is also much faster.

    0 讨论(0)
  • 2021-02-20 16:33

    I would say it's better to bind event to document as in some cases in some browsers body may be missing.

    0 讨论(0)
  • 2021-02-20 16:33

    I'd treat this similarly to anything else in the DOM.

    If I bind to a <table> then it's at a higher level than the <tr> inside it. If I bind to the <tr> then it's lower than the <table>. This works the same way for the document(higher) and the <body>(lower) simply a level issue in my opinion.

    So if you want to ensure that you're binding the click event to the highest element then bind to the document.

    0 讨论(0)
提交回复
热议问题