js实现砖头在页面拖拉效果

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js实现砖头在页面拖拉效果

烽火戏诸诸诸侯   2020-05-15 我要评论

用js实现一个砖头在页面,但鼠标点击拖动时,砖头在页面上形成拖拉效果:

刚开始时:

鼠标点击拖动后:

实现代码:

<html>
  <head>
    <meta charset="utf-8">
    <style type="text/css">
   *{
     margin:0px;
     padding:0px;
    }
  #zhuantou{
    width:120px;
    height:60px;
    background-image:url(1.jpg);
    position:fixed;
    left:100px;
     top:50px;
   }
   </style>
 <body>
   <div id="zhuantou">
   </div>
    <script>
    var zt=document.querySelector("#zhuantou");
    var isPressed=false;
    var offsetX=0;
    var offsetY=0;
    zt.onmousedown=function(event){
         isPressed=true;
         this.style.cursor="move";
         offsetX=event.offsetX;
        offsetY=event.offsetY;
    };
    zt.onmouseup=function(){
       isPressed=false;
       this.style.cursor="default";
    };
    zt.onmousemove=function(event){
      if(!isPressed){
          return;
       }
      zt.style.left=(event.clientX-offsetX)+"px";
     zt.style.top=(event.clientY-offsetX)+"px";
    };
 </script>
 </body>
</html>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们