js实现鼠标拖拽缩放div实例代码
程序员文章站
2023-11-14 13:57:28
封装为了jq插件,如下
drag.js
;(function ($) {
$.fn.dragdiv = function (options) {
va...
封装为了jq插件,如下
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详解整合,希望对大家有所帮助