iOS下的點擊事件失效解決方法

iOS下的點擊事件失效解決方法


問題描述


當委託給一個元素添加click事件時,若是事件是委託到 documentbody 上,而且委託的元素是默認不可點擊的(如 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 改爲 touchendtouchstart(注意加上preventDefault)web

  • click 元素委託到非 documentbody 的父級元素上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)

參考文檔

相關文章
相關標籤/搜索