原生javascript实现左右滑动的平缓效果
原生javascript实现左右滑动的平缓效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#container {
--c-width : 500px;
--c-height : 50px;
width: var(--c-width);
height: var(--c-height);
line-height: var(--c-height);
position: relative;
display: flex;
}
#container .item {
width: calc(var(--c-width) / 2);
height: var(--c-height);
line-height: var(--c-height);
text-align: center;
color: #42b983;
font-size: 20px;
}
#container .item.active {
color: #ffffff;
}
#container #circle {
padding: 5px;
width: calc(var(--c-width) / 2);
height: var(--c-height);
border-radius: calc(var(--c-height)/2);
position: absolute;
transition: transform 0.3s ease-in-out; /* 使用 transform 过渡 */
z-index: -10;
background: #42b983;
}
#container #circle.active {
transform: translateX(calc(var(--c-width) / 2));
}
</style>
</head>
<body>
<div id="container">
<div class="item active">个人版</div>
<div class="item">企业版</div>
<div id="circle"></div>
</div>
</body>
<script>
const items = document.querySelectorAll('.item');
const circle = document.getElementById('circle');
items.forEach((item ) => {
item.addEventListener('click', (event) => {
circle.classList.toggle('active'); // 切换 active 类
items.forEach((value ) => {
value.style.color = '#42b983';
});
event.target.style.color = '#ffffff';
});
})
</script>
</html>
效果图