虽然 以前也写过手机端页面 。当时用的jquery moblie 框架。啥也不懂 就知道复制粘贴出效果 不敢改内部样式。现在呢 了解手机端原理 一些基本的概念 视口 缩放 后 。再去想以前写的页面 套框架 显然得心应手了不少。
手机移动端轮播 原生js
代码:
let banner = document.querySelector('.jd_banner') let imgbox = banner.querySelector('ul:first-of-type')//第一个ul let first = imgbox.querySelector('li:first-of-type') let last = imgbox.querySelector('li:last-of-type') //插入 // 最后的位置 //复制一个 imgbox.appendChild(first.cloneNode(true)) //开始的位置 imgbox.insertBefore(last.cloneNode(true), imgbox.firstChild) let lilist = imgbox.children let bannerWidth = banner.offsetWidth; imgbox.style.width = lilist.length * bannerWidth + 'px' for (let i = 0; i < lilist.length; i++) { lilist[i].style.width = imgbox.offsetWidth / lilist.length + 'px' } imgbox.style.left = -bannerWidth + 'px' let index = 1; //屏幕大小改变 window.onresize = function () { bannerWidth = banner.offsetWidth; imgbox.style.width = lilist.length * bannerWidth + 'px' for (let i = 0; i < lilist.length; i++) { lilist[i].style.width = imgbox.offsetWidth / lilist.length + 'px' } imgbox.style.left = (-index * bannerWidth) + 'px' } let bannerIndex = document.querySelector('.jd_bannerIndex') function active(i) { for (let j = 0; j < bannerIndex.children.length; j++) { bannerIndex.children[j].className = '' } bannerIndex.children[i].className = 'active' } function banntime(){ index++ imgbox.style.transition = 'left 0.5s ease-in-out' imgbox.style.left = (-index * bannerWidth) + 'px' if (index == lilist.length - 1) { active(0) index = 1 setTimeout(function () { imgbox.style.transition = 'none' active(index - 1) imgbox.style.left = (-index * bannerWidth) + 'px' }, 500) } active(index - 1) } let bannerInt = setInterval(banntime, 2000) let startX, moveX, distanceX; imgbox.addEventListener('touchstart', function (e) { startX = e.targetTouches[0].clientX clearInterval(bannerInt) }) imgbox.addEventListener('touchmove', function (e) { moveX = e.targetTouches[0].clientX distanceX = moveX - startX imgbox.style.left = (-index * bannerWidth + distanceX) + 'px' }) imgbox.addEventListener('touchend', function (e) { imgbox.style.transition = 'left 0.5s ease-in-out' let drX = distanceX % bannerWidth if (Math.abs(drX) > bannerWidth / 2) { if (drX > 0) { index-- } else { index++ } if (index == 0) { index = 8 imgbox.style.transition = 'none' } if (index == lilist.length - 1) { index = 1 imgbox.style.transition = 'none' } } active(index - 1) imgbox.style.left = (-index * bannerWidth) + 'px' bannerInt=setInterval(banntime,2000) })
效果:
总结 :
不管什么框架库,还是基本很重要 了解原理 才能得心应手