touchmove不触发,mousemove触发

时间:2018-07-05 13:36:46

标签: javascript css3 touch-event

我得到了这个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>
该代码的目的是您应将蓝色框向下拖动到页面上,当鼠标或触摸在绿色框上时,该绿色框现在将变为红色,它适用于鼠标,但不适用于手机模式下的触摸,这实际上不是我的真实代码,但可以提供足够的信息说明问题所在。

0 个答案:

没有答案