我得到了这个code:
let item1=document.querySelector(".item1");
let item2=document.querySelector(".item2");
let container=document.querySelector(".container");
let posX,posY,startX,startY,move=false;
item1.addEventListener("touchstart",permision1);
item1.addEventListener("mousedown",permision1);
container.addEventListener("touchend",permision2);
container.addEventListener("mouseup",permision2);
item1.addEventListener("touchmove",data);
item1.addEventListener("mousemove",data);
item2.addEventListener("touchmove",changeColor2);
item2.addEventListener("mousemove",changeColor2);
function permision1(e){
e.preventDefault();e.stopPropagation();
item1.style.willChange="transform";
x=e.clientX || e.touches[0].clientX;
y=e.clientY || e.touches[0].clientY;
let rect=item1.getBoundingClientRect();
startX=x-rect.left;
startY=y-rect.top;
move=true;
}
function permision2(e){
e.preventDefault();e.stopPropagation();
item1.style.willChange="auto";
move=false;
}
function data(e){
e.preventDefault();e.stopPropagation();
if(!move)return
posX=e.clientX || e.touches[0].clientX;
posY=e.clientY || e.touches[0].clientY;
requestAnimationFrame(update);
}
function update(){
if(move){
item1.style.transform=`translate3d(${posX-startX}px,${posY-startX}px,0)`;
requestAnimationFrame(update);}
}
function changeColor2(e){
e.preventDefault();e.stopPropagation();
item2.style.backgroundColor="red";
}
*{margin:0;padding:0;border:0;box-sizing:border-box}
.container{
width:100vw;
height:100vh;
}
.item1{
position:fixed;
width:150px;
height:150px;
background-color:blue;
}
.item2{
position:fixed;
top:300px;left:0;
width:200px;
height:200px;
background-color:green;
animation: moving 10s infinite;
}
@keyframes moving {
0% {
transform:translateX(0);
}
50% {
transform:translateX(50vw);
}
100% {
transform:translateX(0);
}
}
<div class="container">
<div class="item1"></div>
<div class="item2"></div>
</div>