jQuery插件实现鼠标拖拽缩放Div宽度

作者:百宝袋时间:2026-10-23 05:49:45浏览:640

本文介绍了一个封装好的jQuery插件,用于实现鼠标拖拽调整Div元素的宽度。通过配置最大和最小宽度参数,结合鼠标移动与释放事件,动态改变容器尺寸,适用于需要交互式调整布局宽度的场景。

jQuery拖拽缩放插件实现

该功能已封装为jQuery插件,具体实现如下所示。

核心逻辑定义在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>

以上即为利用JavaScript实现鼠标拖拽调整Div宽度的完整示例与整合说明,希望能对读者有所帮助。如有任何疑问,欢迎留言,小编将及时回复。同时,感谢大家对本站的支持!

作者最新文章