1.源码:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" /> <style>
.divFixed {
width: 100px;
height: 100px;
font-size: 15px;
text-align: center;
border: 2px solid red;
position: fixed;
}
</style>
<div class="divFixed" id="divOne"></div>
<script>
var divOne = document.getElementById('divOne');
var isMove = false;
var oldX = oldY = 0;
divOne.addEventListener('touchstart', function (e) {
if (e.targetTouches.length == 1) {
var touch = e.targetTouches[0];
isMove = true;
oldX = touch.pageX;
oldY = touch.pageY;
divOne.style.background = "gray";
}
}, false);
divOne.addEventListener('touchmove', function (e) {
if (e.targetTouches.length == 1) {
var touch = e.targetTouches[0];
if (isMove) {
var curX = touch.pageX;
var curY = touch.pageY; divOne.style.left = divOne.offsetLeft + (curX - oldX) + 'px';
divOne.style.top = divOne.offsetTop + (curY - oldY) + 'px'; oldX = curX;
oldY = curY;
}
}
//禁用默认操作
e.preventDefault();
});
divOne.addEventListener('touchend', function (e) {
if (e.changedTouches.length == 1) {
var touch = e.changedTouches[0];
isMove = false;
oldX = oldY = 0;
divOne.style.background = "transparent";
}
}, false); //禁止整个页面触屏,而移动(如:QQ浏览器的页面左右切换)
window.addEventListener('touchmove', function (e) {
e.preventDefault();
}, false);
</script>
2.显示结果: