jquery - 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>
解决方案
试试我为您遇到的问题编写的这个小 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>
推荐阅读
- android - 片段的状态没有被保留
- python - Python:有没有办法找到并删除字符串中第一次和最后一次出现的字符?
- android - 我的数据库有问题:“递归调用getDatabase”
- kubernetes - 在 EKS (Kubernetes) 和 ELB 中使用 gunicorn 和 django 实现高延迟
- bash - '4.5:语法错误:算术运算符无效(错误标记为“.5”)' - 但代码似乎仍然有效。为什么?
- reactjs - 在 Redux 中更新深度嵌套的状态
- kubernetes-helm - Minikube 上的 Helm:更新本地镜像
- r - 为 5 个不同变量的所有可能组合创建平均值
- javascript - 带有 if 语句的 JavaScript for 循环仅检查第一个变量
- angular - Ionic 4 如何从另一个页面获取数据