首页 > 解决方案 > jQuery click 事件在 iPhone 浏览器上不起作用(已经尝试过 cursor:pointer;)

问题描述

我想在我的 wordpress 网站中的锚标签上设置一个点击事件。我能够让它在我的所有设备(PC、Android 手机、平板电脑)上运行,除了我的 iPhone。

我尝试将锚标签的“光标”设置为“指针”无济于事。

我已经尝试了我能在 SO 上找到的所有东西,但似乎没有任何效果:/

任何帮助,将不胜感激。

$("a[href^=#]").on('click touchstart', function(e) {
      e.preventDefault(); var dest = $(this).attr('href');
      console.log(dest);
      $('html,body').animate({ scrollTop: $(dest).offset().top }, 'slow');
    });
.scroller {
        cursor: pointer;
    }
<a href="#res-mobile" class="scroller" onclick="void(0)">
  <div id="mobile-hero-book" class="book-now-btn">Book a Car</div>
</a>

标签: jqueryioscssclick

解决方案


试试我为您遇到的问题编写的这个小 jQuery 插件:

$(document).ready(function() {
  $("#stupid-button").touch(function() {
    console.log("The stupid button was pressed!");
  });
});

$.fn.touch = function(callback) {
  var touch = false;
  $(this).on("click", function(e) {
    if (!touch) {
      console.log("Click detected!");
      let callbackReal = callback.bind(this);
      callbackReal(this, e);
    } else {
      touch = true;
    }
    touch = false;
  });
  $(this).on("touchstart", function(e) {
    $(this).blur();
    if (typeof e.touches != typeof undefined) {
      e.preventDefault();
      touch = true;
      console.log("Touch detected!");
      let callbackReal = callback.bind(this);
      callbackReal(this, e);
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="stupid-button">Click Me</button>

编辑1:

已删除

编辑2:

我误解了这个问题。上面的代码在 iOS 设备上仍然有用,但这里是你应该做的处理锚标签。摆脱#id href:

$(document).ready(function() {
  $(".anchor").touch(function() {
    var targ = $("#" + $(this).data('targ'));
    $('html,body').animate({
      scrollTop: targ.offset().top
    }, 'slow');
  });
});

$.fn.touch = function(callback) {
  var touch = false;
  $(this).on("click", function(e) {
    if (!touch) {
      console.log("Click detected!");
      let callbackReal = callback.bind(this);
      callbackReal(this, e);
    } else {
      touch = true;
    }
    touch = false;
  });
  $(this).on("touchstart", function(e) {
    $(this).blur();
    if (typeof e.touches != typeof undefined) {
      e.preventDefault();
      touch = true;
      console.log("Touch detected!");
      let callbackReal = callback.bind(this);
      callbackReal(this, e);
    }
  });
}
#target-ele {
  margin-top: 1200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="javascript:void(0);" class="anchor" id="link-1" data-targ="target-ele">Click Me</a>

<div id="target-ele">
  <p>This is the target container</p>
</div>


推荐阅读