Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

jquery - How to replace click with touchstart on iOS devices

Objective

To close the parent div of an anchor tag when clicked. In the code below, I want to hide div performance_tt when the user clicks on anchor tag close_performance_tt.

Problem

Unable to get it to work on iOS devices after spending several hours at it. Works fine on everything else, even a BlackBerry 10 device.

<div id="performance_tt" style="display: none;width: 300px;height: 200;overflow: auto;padding: 5px;background-color: yellow;">
    <div>Website performance has become an important consideration for most sites.
    The speed of a website affects usage and user satisfaction, as well as search engine rankings, a factor that directly correlates to revenue and retention.
    As a result, creating a system that is optimized for fast responses and low latency is key.</div>
    <a id="close_performance_tt" href="#">Close</a>
    <script>
    var userAgent = navigator.userAgent.toLowerCase();
    var isiOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
    if (isiOS) {
        $("#close_performance_tt").bind('touchstart', function() {
            alert('Touch-start event triggered');
        });
    } else {
        $("#close_performance_tt").bind('click', function() {
            alert('Click event triggered');
        });
    }
    </script>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Define a clickhandler that you can use later on:

var clickHandler = ('ontouchstart' in document.documentElement ? "touchstart" : "click");

$("a").bind(clickHandler, function(e) {
    alert("clicked or tapped. This button used: " + clickHandler);
});

This will trigger click on non-touch devices and touchstart on touch devices.

When that is said, I will strongly recommend using Fast click instead, and use regular click-events. With the above solution, you will trigger "touchstart" on links when you swipe on it to scroll the page for instance - which is not ideal.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...