实现了基本的效果, 做了个简易的效果, 可以触摸切换
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
div {
width: 100%;
height: 350px;
border: 1px solid red;
max-width: 750px;
margin: 0 300px;
overflow: hidden;
position: relative;
}
ul {
display: flex;
width: 4500px;
position: absolute;
}
ul>li {
list-style: none;
width: 750px;
height: 350px;
border: 1px solid #00FFFF;
}
ul>li:nth-child(1) {
background: url(img/niubi.jpg) no-repeat;
}
ul>li:nth-child(2) {
background: url(img/xuexi.jpg) no-repeat;
}
ul>li:nth-child(3) {
background: url(img/BTB.jpg) no-repeat;
}
ul>li:nth-child(4) {
background: url(img/Miboy.jpg) no-repeat;
}
ul>li:nth-child(5) {
background: url(img/car.jpg) no-repeat;
}
ul>li:nth-child(6) {
background: url(img/niubi.jpg) no-repeat;
}
.trf {
transition: left .4s ease;
}
</style>
</head>
<body>
<div>
<ul class="ul">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script type="text/javascript">
const div = document.querySelector('div')
const ul1 = document.querySelector('.ul')
const lis = document.querySelectorAll('ul li')
let upperindex = 0, lastindex = 0
let Percentage = 0.2, liWidth = 750
let moveP = 0, themove, item = 0
let time = null, path = 0
//设置移动方法
function move(e) {
ul1.classList.remove('trf')
upperindex = parseInt(e.clientX)
themove = e.clientX - 300 + (-moveP) + item
ul1.style.left = themove + 'px'
}
//当点击时添加musemove方法
div.addEventListener('mousedown', e => {
clearTimeout(time)
lastindex = moveP = parseInt(e.offsetX)
div.addEventListener('mousemove', move)
})
//当鼠标抬起时, 删除mousemove方法
div.addEventListener('mouseup', () => {
// console.log(upperindex, lastindex, liWidth * 0.3)
ul1.classList.add('trf')
//判断右边是否碰到末尾
if(item === (-(lis.length-1) * 750)) {
ul1.classList.remove('trf')
ul1.style.left = 0 + 'px'
item = 750
}
//判断滑动方向
if((upperindex - (liWidth * 0.3)) < lastindex) {
console.log('向左滑')
item -= 750
//判断滑动方向
}else if((upperindex + (liWidth * 0.3)) >= lastindex) {
console.log(item)
//判断左边是否末尾
if(item >= 0) {
item = 0
}else {
console.log('向右滑')
item += 750
}
}
ul1.style.left = item + 'px'
div.removeEventListener('mousemove', move)
})
//自动轮播
function mytime() {
ul1.classList.add('trf')
if(path >= lis.length-1) {
path = -1
ul1.classList.remove('trf')
}
path++
ul1.style.left = (path * (-750)) + 'px'
time = setTimeout(mytime, 1000)
}
mytime()
</script>
</body>
</html>