🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
#给拖拽组件配置不同参数 解决参数顺序的问题,可以通过传递一个对象来解决 ``` function show(opt){ } show({ id: 'div1', toDown: function(){}, toUp: function(){} }); ``` 利用对象复制就可以解决参数报错的问题 ``` var a = { name: '小明' }; var b = { name: '小强' }; extend(b, a); alert(b.name); // 小明 有配置参数则使用配置参数 function extend(obj1, obj2) { for (var attr in obj2) { obj1[attr] = obj2[attr]; } } ``` ``` var a = { // 配置参数 // name: '小明' }; var b = { // 默认参数 name: '小强' }; extend(b, a); alert(b.name); // 小强 没有配置参数则使用默认参数 function extend(obj1, obj2) { for (var attr in obj2) { obj1[attr] = obj2[attr]; } } ``` 给拖拽组件配置不同参数 ``` <style> #div1, #div2, #div3, #div4{ width: 100px; height: 100px; position: absolute; } #div1{ background: #c40000; } #div2{ background: green; left: 100px; } #div3{ background: brown; left: 200px; } #div4{ background: blue; left: 300px; } </style> <script> window.onload = function () { var d1 = new Drag(); d1.init({ // 配置参数 id: 'div1' }); var d2 = new Drag(); d2.init({ // 配置参数 id: 'div2', toDown: function () { document.title = 'hello'; } }); var d3 = new Drag(); d3.init({ // 配置参数 id: 'div3', toDown: function () { document.title = '妙味'; }, toUp: function () { document.title = '课堂'; } }); var d4 = new Drag(); d4.init({ // 配置参数 id: 'div4', toUp: function () { document.title = 'byebye'; } }); }; function Drag() { this.obj = null; this.disX = 0; this.disY = 0; this.settings = { // 默认参数 toDown: function(){}, toUp: function(){} }; } Drag.prototype.init = function (opt) { var _this = this; this.obj = document.getElementById(opt.id); // 用配置参数去覆盖默认参数 extend(this.settings, opt); this.obj.onmousedown = function (e) { var e = e || window.event; _this.fnDown(e); _this.settings.toDown(); // 调用的时候是调用的默认参数 document.onmousemove = function (e) { var e = e || window.event; _this.fnMove(e); }; document.onmouseup = function () { _this.fnUp(); _this.settings.toUp(); // 调用的时候是调用的默认参数 }; return false; }; }; Drag.prototype.fnDown = function (e) { this.disX = e.clientX - this.obj.offsetLeft; this.disY = e.clientY - this.obj.offsetTop; }; Drag.prototype.fnMove = function (e) { this.obj.style.left = e.clientX - this.disX + 'px'; this.obj.style.top = e.clientY - this.disY + 'px'; }; Drag.prototype.fnUp = function () { document.onmousemove = null; document.onmouseup = null; }; function extend(obj1, obj2) { for (var attr in obj2) { obj1[attr] = obj2[attr]; } } </script> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> <div id="div4"></div> ```