当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js实现盒子拖拽动画效果

js实现盒子拖拽动画效果

2020年08月10日  | 移动技术网IT编程  | 我要评论
本文实例为大家分享了js实现盒子拖拽动画的具体代码,供大家参考,具体内容如下<!doctype html><html lang="zh-cn"><head> <

本文实例为大家分享了js实现盒子拖拽动画的具体代码,供大家参考,具体内容如下

<!doctype html>
<html lang="zh-cn">
<head>
 <meta charset="utf-8">
 <title>document</title>
 <script src="jquery.js"></script>
 <style>
 * {
  margin: 0;
  padding: 0;
 }
 .wrap {
  width: 400px;
  height: 200px;
  border: 1px solid #ccc;
  border-right-color: red;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -200px;
  margin-top: -100px;
  box-sizing: border-box;
 }
 .wrap .head {
  height: 40px;
  padding-left: 4px;
  padding-right: 4px;
  background-color: #ccc;
  box-sizing: border-box;
  line-height: 40px;
  user-select: none;
 }
 .head:hover {
  cursor: move;
 }
 .head span {
  float: left;
 }
 #close {
  float: right;
 }
 #close:hover {
  cursor: pointer;
 }
 </style>
</head>
<body>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <p>tom</p>
 <div class="wrap">
 <div class="head">
  <span>试着拖拽我</span>
  <span id="close">【关闭】</span>
 </div>
 </div>
 <script>
 let wrap = document.queryselector('.wrap');
 let close = document.getelementbyid('close');
 let head = document.queryselector('.head');

 head.onmousedown = function (e) {
  // 获得鼠标在 head 中的坐标 
  let x = e.pagex - wrap.offsetleft;
  let y = e.pagey - wrap.offsettop;
  console.log(x, y);
  document.onmousemove = function (e) {
  
  let xx = e.pagex - x;
  let yy = e.pagey - y;
  // 设置边界限制
  xx = xx < 0 ? 0 : xx;
  yy = yy < 0 ? 0 : yy;
  if (xx >= innerwidth - wrap.offsetwidth) {
   document.documentelement.scrollleft = 20;
  } else {
   document.documentelement.scrollleft = 0;
  }
  xx = xx > innerwidth - wrap.offsetwidth ? innerwidth-wrap.offsetwidth : xx; 
  yy = yy > innerheight - wrap.offsetheight + document.documentelement.scrolltop ? innerheight - wrap.offsetheight + document.documentelement.scrolltop : yy;
  wrap.style.left = xx + 'px';
  wrap.style.top = yy + 'px';
  // 禁止x滚动轴
  document.body.style.overflowx = 'hidden';
  wrap.style.marginleft = 0;
  wrap.style.margintop = 0;
  };
 };

 document.onmouseup = function () {
  document.onmousemove = null;
 };

 close.onclick = function () {
  wrap.style.display = 'none';
 };
 </script>
</body>
</html>

实现效果:

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

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网