旨在提供一种思路,我这里给了四个item,宽度也是在css写死的。要作为组件使用的话,各个item的宽度、top值、left值都是需要使用js计算的,好了,废话不多说直接上代码,上面都有注释
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.slider-3d {
position: relative;
width: 900px;
margin: 50px auto;
}
.slider-item {
position: absolute;
box-shadow: 10px 20px 10px rgba(0, 0, 0, 0.6);
transition: all 0.6s cubic-bezier(0.39, 0.575, 0.565, 1);
}
.slider-item.left {
width: 250px;
z-index: 2;
opacity: 0.7;
transform: translate3d(0, 150px, 0);
}
.slider-item.center {
width: 500px;
z-index: 3;
transform: translate3d(200px, 80px, 0);
}
.slider-item.right {
width: 250px;
z-index: 2;
opacity: 0.7;
transform: translate3d(650px, 150px, 0);
}
.slider-item.top {
width: 300px;
z-index: 1;
opacity: 0.5;
transform: translate3d(300px, 0, 0);
}
img {
display: block;
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<div class="slider-3d">
<div class="slider-item center" data-index="0">
<img src="./assets/img/1.jpg" alt="" />
</div>
<div class="slider-item right" data-index="1">
<img src="./assets/img/2.jpg" alt="" />
</div>
<div class="slider-item top" data-index="2">
<img src="./assets/img/3.jpg" alt="" />
</div>
<div class="slider-item left" data-index="3">
<img src="./assets/img/4.png" alt="" />
</div>
</div>
</div>
</body>
<script>
const sliderList = document.querySelectorAll('.slider-item'),
oClassNames = []
let t = null
function getClassNames() {
for (let i = 0; i < sliderList.length; i++) {
oClassNames.push(sliderList[i].className)
}
}
function handleHoverItem() {
for (let i = 0; i < sliderList.length; i++) {
sliderList[i].addEventListener('mouseenter', e => {
stop()
console.log(e)
console.log(e.target.dataset.index)
console.log(oClassNames)
if (e.target.className === 'slider-item center') {
return
}
for (let i = 0; i < oClassNames.length; i++) {
oClassNames.unshift(oClassNames.pop())
if (oClassNames[e.target.dataset.index] === 'slider-item center') {
break
}
}
console.log(oClassNames)
setClass()
sliderList[i].addEventListener('mouseleave', e => {
stop()
run()
})
})
}
}
function setClassName() {
oClassNames.unshift(oClassNames.pop())
setClass()
}
function setClass() {
for (let i = 0; i < sliderList.length; i++) {
sliderList[i].className = oClassNames[i]
}
}
function run() {
t = setInterval(() => {
setClassName()
}, 3000)
}
function stop() {
clearInterval(t)
t = null
}
function init() {
getClassNames()
handleHoverItem()
run()
}
init()
</script>
</html>
效果预览:
|