网络编程 
首页 > 网络编程 > 浏览文章

JS+DIV实现拖动效果

(编辑:jimmy 日期: 2024/11/8 浏览:3 次 )

本文实例为大家分享了JS+DIV实现拖动效果的具体代码,供大家参考,具体内容如下

效果图

JS+DIV实现拖动效果

思路

JS+DIV实现拖动效果

代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="main" style="background-color: aqua;width: 100px;height: 100px;position: absolute;left: 50px;top: 50px">
  <div id="title" style="height: 10px;width:100%;background-color: antiquewhite;position: absolute;left: 0px;top: 0px"></div>
  <div class="box"></div>
</div>
<script>

  var startx;
  var starty;
  var startLeft;
  var startTop;
  var titleDiv=document.getElementById("title");
  var mainDiv=document.getElementById("main");
  var isDown=false;
//  鼠标按下
  function movedown(e){
    e=e"px";
      mainDiv.style.top = e.clientY - (starty - startTop)+"px";
    }
  }
//  鼠标松开
  function moveup(){
    isDown=false;
  }
  titleDiv.οnmοusedοwn=movedown;
  titleDiv.οnmοusemοve=move;
  titleDiv.οnmοuseup=moveup;
</script>
</body>
</html>

优化(封装,以及解决拖动问题(事件捕获))

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="main" style="background-color: aqua;width: 100px;height: 100px;position: absolute;left: 50px;top: 50px">
  <div id="title"
     style="height: 10px;width:100%;background-color: antiquewhite;position: absolute;left: 0px;top: 0px"></div>
  <div class="box"></div>
</div>
<script>


  function Mover(title) {
    this.obj = title;
    this.startx = 0;
    this.starty;
    this.startLeft;
    this.startTop;
    this.mainDiv = title.parentNode;
    var that = this;
    this.isDown = false;
    this.movedown = function (e) {
      e = e "px";
        that.mainDiv.style.top = e.clientY - (that.starty - that.startTop) + "px";
      }
    }
    this.moveup = function () {
      that.isDown = false;
      if (!window.captureEvents) {
        this.releaseCapture();
      } //事件捕获仅支持ie
    }
    this.obj.onmousedown = this.movedown;
    this.obj.onmousemove = this.move;
    this.obj.onmouseup = this.moveup;

    //非ie浏览器
    document.addEventListener("mousemove", this.move, true);
  }
  var mover = new Mover(document.getElementById("title"));


  //写两个是为了解决 ie 和非ie 浏览器关于事件捕获 的兼容性问题


</script>
</body>
</html>

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

上一篇:node.js实现http服务器与浏览器之间的内容缓存操作示例
下一篇:vue项目中使用particles实现粒子背景效果及遇到的坑(按钮没有点击响应)