Skip to content

Instantly share code, notes, and snippets.

@ufologist
Created September 19, 2014 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufologist/b023b4dd732a318c5c0d to your computer and use it in GitHub Desktop.
Save ufologist/b023b4dd732a318c5c0d to your computer and use it in GitHub Desktop.
fixbug: touchend doesn't fire on mobile devices
<!DOCTYPE html>
<html>
<head>
<title>touchend doesn't fire on mobile devices</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<style>
body {
background-color: #eee;
}
.headline {
font-size: 1.5em;
}
.headline small {
display: block;
}
.touchme {
height: 180px;
line-height: 180px;
margin-bottom: 10px;
background-color: #4E9197;
text-align: center;
font-size: 3em;
-webkit-user-select: none;
box-shadow: 0 2px 5px #aaa;
border-radius: 5px;
}
.textarea-log {
width: 100%;
}
.author {
border-top: 1px dashed #aaa;
padding-top: 10px;
text-align: right;
color: #999;
font-size: small;
}
blockquote a {
display: block;
}
</style>
</head>
<body>
<h1 class="headline">FIXBUG: touchend doesn't fire <small>on mobile devices</small></h1>
<div class="touchme">touch me</div>
<textarea class="textarea-log" cols="30" rows="10"></textarea>
<input type="checkbox" id="js-fixtouch"><label for="js-fixtouch">fix touch event problem</label>
<p class="author">2014-9-19 Sun</p>
<ul>
<li><a href="http://code.google.com/p/android/issues/detail?id=19827">WebView touchevents are not fired propperly if e.preventDefault() is not used on touchstart and touchmove</a></li>
<li><a href="http://blog.mobiscroll.com/working-with-touch-events/">Working with touch events</a></li>
</ul>
<script>
var touchEl = document.querySelector('.touchme');
var logEl = document.querySelector('.textarea-log');
var fixtouchEl = document.querySelector('#js-fixtouch');
function logEvent(type) {
logEl.innerHTML = logEl.innerHTML + '\n' + new Date().toLocaleTimeString() + ' - ' + type;
logEl.scrollTop = logEl.scrollHeight;
}
touchEl.addEventListener('touchstart', function(event) {
logEvent('[touchstart]');
// 在touchstart中阻止事件的默认行为即可修复touchmove和touchend事件不触发的问题
if (fixtouchEl.checked) {
event.preventDefault();
}
}, false);
touchEl.addEventListener('touchmove', function(event) {
logEvent('touchmove');
}, false);
touchEl.addEventListener('touchend', function(event) {
logEvent('[touchend]');
}, false);
</script>
</body>
</html>
Copy link

ghost commented Jan 16, 2015

demo中的 event.preventDefault() 更适合添加在 touchmove 事件中。

@superfighter
Copy link

阻止默认事件不是不能滚动了吗?长页面滚动到底这怎么搞?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment