温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js怎么实现鼠标拖拽缩放div

发布时间:2021-04-20 09:41:41 来源:亿速云 阅读:591 作者:小新 栏目:web开发

这篇文章主要介绍js怎么实现鼠标拖拽缩放div,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

js有什么特点

1、js属于一种解释性脚本语言;2、在绝大多数浏览器的支持下,js可以在多种平台下运行,拥有着跨平台特性;3、js属于一种弱类型脚本语言,对使用的数据类型未做出严格的要求,能够进行类型转换,简单又容易上手;4、js语言安全性高,只能通过浏览器实现信息浏览或动态交互,从而有效地防止数据的丢失;5、基于对象的脚本语言,js不仅可以创建对象,也能使用现有的对象。

drag.js

;(function ($) {
 $.fn.dragDiv = function (options) {
  var def = {
   maxW:600,// 可伸缩的最大宽度
   minW:50// 可伸缩的最小宽度
  };// 参数默认值
  var opts = $.extend(def,options);// 扩展参数,使用默认值或传参
  //设置最大/最小宽度
  var max_width = opts.maxW,
   min_width = opts.minW;
 
  //记录鼠标相对left盒子x轴位置
  var mouse_x = 0;
  var left = $(this).parent('div')[0];
 
  //鼠标移动事件
  function mouseMove(e) {
   var e = e || window.event;
   var left_width = e.clientX - mouse_x;// 可伸缩div的宽度
   left_width = left_width < min_width ? min_width : left_width;
   left_width = left_width > max_width ? max_width : left_width;
   left.style.width = left_width + "px";
  }
  //终止事件
  function mouseUp() {
   document.onmousemove = null;
   document.onmouseup = null;
  }
  $(this).mousedown(function (e) {
   var e = e || window.event;
   //阻止默认事件
   e.preventDefault();
   mouse_x = e.clientX - left.offsetWidth;// 可伸缩div距离左侧边界的宽度
   document.onmousemove = function () {
    mouseMove()
   };
   document.onmouseup = function () {
    mouseUp()
   };
  })
 }
})(jQuery)

html文件

<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport"
   content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>鼠标进行伸缩div</title>
 <style>
  * {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
  }
  .dragdom {
   background: #cccccc;
   width: 100px;
   height: 600px;
   margin: 0 auto;
   position: relative;
  }
  .dragdom .drag {
   border: 1px transparent solid;
   width: 0px;
   height: 100%;
   position: absolute;
   top: 0;
   right: 0;
   cursor: e-resize;
  }
 </style>
</head>
<body>
<div class="dragdom"><div class="drag"></div></div>
</body>
</html>
<script type="text/javascript" src="./jquery.min.js"></script>
<script type="text/javascript" src="./drag.js"></script>
<script>
 $(function () {
  $('.drag').dragDiv();
 })
</script>

以上是“js怎么实现鼠标拖拽缩放div”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI