富贵资源网 Design By www.hznty.com

一、JS 拖拽的实现实例代码:

<!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8" />
 <title>拖拽js</title>
 <style type="text/css">
 html, body {
 overflow:hidden;
 }
 body, div, {
 margin:0;
 padding:0;
 }
 body {
 color:#fff;
 font:12px/2 Arial;
 }
 p {
 padding:0 10px;
 margin-top:10px;
 }
 span {
 color:#ff0;
 padding-left:5px;
 }
 #box {
 position:absolute;
 width:300px;
 height:150px;
 background:#D5CDDA;
 border:2px solid #ccc;
 top:150px;
 left:400px;
 margin:0;
 }
 #drag {
 height:25px;
 cursor:move;
 background:#724a88;
 border-bottom:2px solid #ccc;
 padding:0 10px;
 }

</style>
</head>
<body>
<div id="box">
 <div id="drag">拖动区域</div>
 被拖动的整个div
 </div>
</body>
</html>

<script src="/UploadFiles/2021-04-02/jquery-1.10.1.min.js">https://www.jb51.net/article/93142.htm

效果图如下:

JavaScript 拖拽实例代码

突然发现有没有效果图都一样哈哈,不说废话了,上代码:

html代码:

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf8">
 <title>js拖拽效果</title>
 <style type="text/css">
 #div1 {
  width : 200px;
  height: 200px;
  position: absolute;
  background: #99dd33;
  cursor: move;
 }
 </style>
</head>
<body>
 <div id="div1"></div>
</body>
<script type="text/javascript">
 // js代码
</script>
</html>

js代码:

window.onload function() {
 var disX = disY = 0;       // 鼠标距离div的左距离和上距离
 var div1 = document.getElementById("div1"); // 得到div1对象
 
 // 鼠标按下div1时
 div1.onmousedown = function(e) {
  var evnt = e || event;     // 得到鼠标事件
  disX = evnt.clientX - div1.offsetLeft; // 鼠标横坐标 - div1的left
  disY = evnt.clientY - div1.offsetTop; // 鼠标纵坐标 - div1的top
  
  // 鼠标移动时
  document.onmousemove = function(e) {
   var evnt = e || event;
   var x = evnt.clientX - disX;
   var y = evnt.clientY - disY;
   var window_width = document.documentElement.clientWidth - div1.offsetWidth;
   var window_height = document.documentElement.clientHeight - div1.offsetHeight;
   
   x = ( x < 0 ) "px";
   div1.style.top = y + "px";
  };
  
  // 鼠标抬起时
  document.onmouseup = function() {
   document.onmousemove =null;
   document.onmouup = null;
  };
  
  return false;
 };
};

 当然,这个虽然支持大部分浏览器,但是,我觉得div跟随鼠标的速度有点滞后,如果有好的解决办法请联系我喔,谢谢!

以上就是js实现拖拽的实例代码,有需要的小伙伴可以参考下,谢谢大家对本站的支持!

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com