移动端js写法

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
<title></title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}

html {
font-size: 20px;
}

#wrap {
width: 16rem;
height: 7.5rem;
margin: 0 auto;
overflow: hidden;
}

#wrap ul {
width: 64rem;
height: 7.5rem;
}

#wrap ul li {
font-size: 2rem;
color: #fff;
width: 16rem;
height: 7.5rem;
float: left;
text-align: center;
line-height: 7.5rem;
}
</style>
<script>
(function (win, doc) {
function change() {
doc.documentElement.style.fontSize = 20 * doc.documentElement.clientWidth / 320 + 'px';
}

change();
win.addEventListener('resize', change, false);
})(window, document);

document.addEventListener('DOMContentLoaded', function () {
var oUl = document.querySelectorAll('#wrap ul')[0];
var aLi = oUl.children;
var x = 0;
var iNow = 0;
oUl.addEventListener('touchstart', function (ev) {
var downX = ev.targetTouches[0].pageX;
var disX = downX - x;

function move(ev) {
x = ev.targetTouches[0].pageX - disX;
oUl.style.WebkitTransform = 'translate3d(' + x + 'px,0,0)';
}
function end(ev) {
oUl.removeEventListener('touchmove', move, false);

oUl.removeEventListener('touchend', end, false);
oUl.style.WebkitTransition = 'all 300ms ease';
var upX = ev.changedTouches[0].pageX;

if (Math.abs(upX - downX) > 100) {//切换到下一张;
if (downX > upX) {
iNow++;
if (iNow == aLi.length)iNow = aLi.length - 1;
} else {
iNow--;
if (iNow == -1)iNow = 0;
}
}
x = -iNow * aLi[0].offsetWidth;
oUl.style.WebkitTransform = 'translate3d(' + x + 'px,0,0)';
}

oUl.addEventListener('touchmove', move, false);

oUl.addEventListener('touchend', end, false);

ev.preventDefault();
}, false);

}, false);
</script>
</head>
<body>
<div id="wrap">
<ul>
<li style="background: red;">0</li>
<li style="background: #1a3cff;">1</li>
<li style="background: #66ff11;">2</li>
<li style="background: #ff127e;">3</li>
</ul>
</div>
</body>
</html>

posted @ 2016-12-29 00:28  李鱼儿家  阅读(306)  评论(0编辑  收藏  举报