当前位置:Gxlcms > JavaScript > js实现砖头在页面拖拉效果

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

时间:2021-07-01 10:21:17 帮助过:3人阅读

用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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行