當委託給一個元素添加click事件時,若是事件是委託到 document
或 body
上,而且委託的元素是默認不可點擊的(如 div, span 等),此時 click 事件會失效。css
demo:html
<!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <meta name="robots" content="index,follow"/> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"> <meta name="apple-mobile-web-app-status-bar-style" content="black"/> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="format-detection" content="telphone=no, email=no"> <meta name="renderer" content="webkit"> <meta http-equiv="Cache-Control" content="no-siteapp" /> <meta name="HandheldFriendly" content="true"> <meta name="MobileOptimized" content="320"> <meta name="screen-orientation" content="portrait"> <meta name="x5-orientation" content="portrait"> <meta name="full-screen" content="yes"> <meta name="x5-fullscreen" content="true"> <meta name="browsermode" content="application"> <meta name="x5-page-mode" content="app"> <meta name="msapplication-tap-highlight" content="no"> <meta http-equiv="Expires" content="0"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Cache-control" content="no-cache"> <meta http-equiv="Cache" content="no-cache"> </head> <body> <div class="container"></div> <div class="target">點擊我!</div> </div> <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script> <script> $(function () { // $(document).on('click', '.target', function () {}) $('body').on('click', '.target', function () { alert('我被點擊了!!!'); }); }); </script> </body> </html>
解決辦法有6種:react
將 click
事件直接綁定到目標元素(即 .target
) 上jquery
將目標元素換成 <a>
或者 <button>
等可點擊的元素git
給目標元素添加一個空的 onclick=""
(<div class="target" onclick="">點擊我!</div>)github
把 click
改爲 touchend
或 touchstart
(注意加上preventDefault)web
將 click
元素委託到非 document
或 body
的父級元素上chrome
給目標元素加一條樣式規則 cursor: pointer;
(cursor: pointer; -webkit-tap-highlight-color: transparent;)app
推薦後兩種。推測在 Safari 中,不可點擊元素的點擊事件是不會冒泡到父級元素的。經過添加 cursor: pointer;
使得元素變成了可點擊的了。iphone
iOS系統 input
及 input內元素 cursor: pointer;
失效,使得在 iOS系統 上須要藉助 cursor
屬性才能生效的 click
事件沒法觸發
設置 font-size: 0;
把 click
改爲 touchend
(注意加上preventDefault)