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
415 views
in Technique[技术] by (71.8m points)

javascript - Why onclick event suppressed, when preventDefault() is called for the touchstart event?

I try to implement some javascript functions for my Ipad device. I would like to use some swipe action and click action on my canvas div.

I implemented the horizontal and the vertical swipe function. I have to use the preventDefault on the touchstart event to prevent the full page scrolling, when swiping. It worked well, but after this I noticed that it disabled every click event on this div. When the preventDefault is removed the click event works again.

Is there any solution to solve this problem?

dojo.connect(this.node, "ontouchstart", this, "touchstart"); 

...   

touchstart: function(e){
    this.touch = dojo.clone(e.changedTouches[0]);
    e.preventDefault();   
}

this.node = document.getElementById('aa');

<div id="aa" style="width: 600px; height: 400px;">
  <div onclick="alert('asd');" style="width: 100px; height: 100px; background-color: #ff0000; margin: auto;">

  </div>
</div>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I know Prusse has already answered this question correctly, but it lacks the confidence I search for in an answer. The reason the click event suppressed by preventDefault() in touchstart is because any event connected and following touchstart will be suppressed. The solution is to add preventDefault() to the touchmove event instead.

This is explained in more detail in the Mozilla documentation under Handling Clicks:

Since calling preventDefault() on a touchstart or the first touchmove event of a series prevents the corresponding mouse events from firing, it's common to call preventDefault() on touchmove rather than touchstart. That way, mouse events can still fire and things like links will continue to work.


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

...