我们想要使用手指的滑动事件来改变屏幕中元素的位置,同时滑动了多少也通过元素展现出来
通过移动端事件让着四个头像轮流替换位置,同时的刷新圆圈跟着手指滑动的距离旋转
首先HTML部分给每个图片一个id进行标识,再通过类名定位,再给一个1秒钟的过渡动画,通过滑动把类名给予不同的id让头像达到换位的效果
<div id="content">
<span id="touXiang">选择你的头像</span>
<img src="./img/Adam.png" id="head1" class="pot1">
<img src="./img/Cary.png" id="head2" class="pot2">
<img src="./img/Kumaio.png" id="head3" class="pot3">
<img src="./img/Nakia.png" id="head4" class="pot4">
<img src="./img/刷新.png" id="refresh">
</div>
css部分
#content {
display: flex;
height: 100vh;
width: 100vw;
justify-content: center;
align-items: center;
background-color: cadetblue;
}
img {
width: 15vw;
transition: all 1s linear;
}
#refresh {
position: absolute;
top: 80%;
}
#touXiang {
font-size: 20px;
font-weight: 600;
position: absolute;
top: 15%;
}
.pot1 {
position: absolute;
width: 15vw;
filter: grayscale(0%);
z-index: 1;
}
.pot2 {
position: absolute;
top: 40%;
left: 20%;
width: 10vw;
filter: grayscale(80%);
}
.pot3 {
position: absolute;
top: 40%;
left: 70%;
width: 10vw;
filter: grayscale(80%);
}
.pot4 {
position: absolute;
top: 30%;
width: 8vw;
filter: grayscale(80%);
再用就是js部分,让我们先定义一个角度的对象,再使用defineProperty创建一个新的属性,用get和set方法操作属性把value也就是滑动的距离绑定给角度达到旋转的效果
let unlock = true // false停下
let data = {
_jiaodu:0
}
// 给对象里的角度定义一个新属性
Object.defineProperty(data,"jiaodu",{
get:function(){
return this._jiaodu
},
set:function(value){
if (value != this._jiaodu) {
this._jiaodu = value
refresh.style.transform = `rotateZ(${this._jiaodu}deg)`
}
}
})
声明两个数组,一个数组放id,一个数组放数字等下通过遍历数字拼接类名达到变换位置的效果
不需要数组也可以使用数组的插入删除方法达到同样的效果,把最后一个删掉再添加到数组的第一位达到循环的效果
// 把旋转的头像id放在数组里
let idIndex = ["head4","head3","head2","head1"]
let nErr = [1,2,3,4]
按下滑动的方法
// 手指按下事件
content.ontouchstart = function(e) {
this.startX = e.touches[0].clientX
}
// 手指滑动事件
content.ontouchmove = function(e) {
this.moveX = e.touches[0].clientX
// 旋转的角度
data.jiaodu += (this.moveX - this.startX)
}
手指抬起离开进行判断,手指抬起的位置减去手指落下的位置等于移动的距离,大于50开始循环数组,当数组的i等于4末尾的时候再重新赋值为1否则继续加加 左右同理,每次滑动触发一次遍历拼接类名
// 手指离开事件
content.ontouchend = function(e) {
// 手指离开的参数
let endX = e.changedTouches[0].clientX
if (unlock) {
// 离开减去开始的大于小于50
if (endX - this.startX >= 50) {
unlock = false
for (let i = 0; i < nErr.length; i++) {
// 类似于轮播图无缝衔接的算法 到最后一张图片了就赋值为1
if (nErr[i] == 4) {
nErr[i] = 1
} else {
nErr[i]++
}
}
} else if(endX - this.startX <= -50){
unlock = false
for (let i = 0; i < nErr.length; i++){
if (nErr[i] == 1) {
nErr[i] = 4
}else {
nErr[i]--
}
}
}
// 数组数组拼接类名 改变位置
for (let i = 0; i < nErr.length; i++){
console.log(nErr[i]);
document.getElementById(idIndex[i]).className = "pot" + nErr[i];
}
// 自动解开锁
if (!unlock){
setTimeout(()=>{
unlock = true
},2000)
}
}
data.jiaodu += (endX - this.startX)
}