js用move实现页面左右切换
时间: 2024-02-28 19:54:35 浏览: 36
您可以使用JavaScript中的move()函数来实现页面左右切换。这个函数可以接受两个参数,第一个参数是要移动的元素的DOM对象,第二个参数是要移动的距离。
以下是一个示例代码,实现当点击左右箭头时,页面向左或向右移动:
HTML代码:
```
<div class="container">
<div class="page">Page 1</div>
<div class="page">Page 2</div>
<div class="page">Page 3</div>
</div>
<button id="prevBtn">上一页</button>
<button id="nextBtn">下一页</button>
```
CSS代码:
```
.container {
width: 300px;
overflow: hidden;
white-space: nowrap;
}
.page {
display: inline-block;
width: 300px;
height: 200px;
}
#prevBtn, #nextBtn {
display: inline-block;
margin-top: 20px;
}
```
JavaScript代码:
```
var container = document.querySelector('.container');
var pages = document.querySelectorAll('.page');
var prevBtn = document.getElementById('prevBtn');
var nextBtn = document.getElementById('nextBtn');
var pageIndex = 0;
var pageWidth = pages[0].offsetWidth;
prevBtn.addEventListener('click', function() {
pageIndex--;
if (pageIndex < 0) {
pageIndex = 0;
}
move(container, -pageIndex * pageWidth);
});
nextBtn.addEventListener('click', function() {
pageIndex++;
if (pageIndex > pages.length - 1) {
pageIndex = pages.length - 1;
}
move(container, -pageIndex * pageWidth);
});
function move(element, distance) {
var duration = 500; // 移动持续时间
var interval = 10; // 移动时间间隔
var frames = duration / interval; // 移动帧数
var speed = distance / frames; // 移动速度
var left = element.offsetLeft; // 当前距离左侧的距离
var to = left + distance; // 移动到的目标位置
function animate() {
if ((distance > 0 && left < to) || (distance < 0 && left > to)) {
left += speed;
element.style.left = left + 'px';
setTimeout(animate, interval);
} else {
element.style.left = to + 'px';
}
}
animate();
}
```
在这个示例中,我们首先获取了容器元素和页面元素,然后为左右箭头绑定了点击事件。当点击左箭头时,pageIndex减1,当点击右箭头时,pageIndex加1。然后调用move()函数,将容器元素向左或向右移动到对应的页面位置。
在move()函数中,我们计算了移动的速度和距离,然后使用递归函数实现了动画效果。在每一帧中,我们都将容器元素的left值加上移动速度,从而实现了平滑的移动效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)