js在滑动触摸结束后,左滑背景色周期变换红绿蓝红,右滑背景色周期变换红蓝绿红,上滑下滑不变色,滑一次变一次色
时间: 2024-05-15 18:15:56 浏览: 12
可以通过以下代码实现:
```javascript
let colorIndex = 0; // 当前背景色的索引
const colors = [
['red', 'green', 'blue'], // 左滑背景色周期
['red', 'blue', 'green'], // 右滑背景色周期
];
function changeColor(direction) {
if (direction === 'left') {
document.body.style.backgroundColor = colors[0][colorIndex];
} else if (direction === 'right') {
document.body.style.backgroundColor = colors[1][colorIndex];
}
colorIndex = (colorIndex + 1) % 3; // 循环更新索引
}
let startX, startY;
document.addEventListener('touchstart', function(e) {
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
});
document.addEventListener('touchend', function(e) {
const endX = e.changedTouches[0].clientX;
const endY = e.changedTouches[0].clientY;
const deltaX = endX - startX;
const deltaY = endY - startY;
if (Math.abs(deltaX) > Math.abs(deltaY)) { // 左右滑动
if (deltaX < 0) { // 左滑
changeColor('left');
} else { // 右滑
changeColor('right');
}
}
});
```
解析:
1. 定义 `colorIndex` 变量表示当前背景色的索引,初始值为 0。
2. 定义 `colors` 数组表示左滑和右滑的背景色周期。
3. 定义 `changeColor` 函数接收一个字符串参数 `direction`,表示滑动方向,根据方向和当前 `colorIndex` 更新背景色。
4. 在 `touchstart` 事件中记录起始坐标。
5. 在 `touchend` 事件中计算滑动距离,如果横向滑动距离大于纵向滑动距离,则判断滑动方向,调用 `changeColor` 函数更新背景色。
6. `colorIndex` 每次更新后取模 3,以保证循环更新背景色。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)