元素大小縮放是一套連貫事件,按下鼠標不放,拖動鼠標 然后松開。
按下鼠標事件
當按下鼠標時,記錄元素大小、鼠標按下的位置、狀態位。
拖動鼠標事件
當鼠標拖動時,計算元素調用后的大小。
元素調整后大小 = 初始元素大小 + (鼠標移動位置 - 鼠標按下位置)
鼠標松開事件
當調整完成后,鼠標松開這時重置狀態位,防止移動鼠標時觸發移動事件。
'use strict'; class DivElement { /** * 構造函數 * @param {object} option * @param {HTMLElement} option.element * @param {number} option.minwidth * @param {number} option.minheight */ constructor({ element, minwidth, minheight }) { this.element = element; this.minheight = minheight; this.minwidth = minwidth; this.state = false; } /** * @returns {CSSStyleDeclaration} */ get style() { return window.getComputedStyle(this.element); } /** * 調整大小 */ resizable() { let nodese = this._createSe('resizable-se'); let [mousedownX, mousedownY, width, height] = [0, 0, 0, 0]; // 鼠標按下 nodese.addEventListener("mousedown", (event) => { this.state = true; // 設置狀態位 [mousedownX, mousedownY, width, height] = [ event.clientX, // 鼠標按下時X坐標 event.clientY, // 鼠標按下時Y坐標 Number.parseFloat(this.style.width), // 獲取元素寬度 Number.parseFloat(this.style.height), // 獲取 元素高度 ]; }); // 鼠標拖動 document.addEventListener("mousemove", (event) => { if (this.state) { let w = width + (event.clientX - mousedownX); // 調整后的寬度 let h = height + (event.clientY - mousedownY); // 調整后的高度 if (w > this.minwidth) { // 限制最小 寬度 this.element.style.width = w + 'px'; } if (h > this.minheight) { // 限制最小 高度 this.element.style.height = h + 'px'; } } }) // 鼠標松開 this.element.addEventListener("mouseup", (event) => { this.state = false; // 重置狀態位 }) } _createSe(className) { let node = document.createElement('div'); node.className = className; this.element.appendChild(node); return node; } }
<!DOCTYPE html> <head> <meta charset="utf8"> <title>縮放</title> <script src="DivElement.js"></script> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="resizable"> <h2>右下角</h2> </div> <script> 'use strict'; let o = new DivElement({ element: document.querySelector('.resizable'), minwidth: 140, minheight: 140 }); o.resizable(); </script> </body> </html>
.resizable { border: 1px #ccc solid; float: left; height: 200px; width: 200px; padding: 40px; position: relative; } .resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; background: url("ui-icons.png") no-repeat; position: absolute; }
樣本:http://js.zhuamimi.cn/%E5%85%83%E7%B4%A0%E5%A4%A7%E5%B0%8F%E8%B0%83%E6%95%B4/
源碼:https://pan.baidu.com/s/1f4n0NK6QzFnQokMSWf7kEg
我的百度經驗:https://jingyan.baidu.com/article/1876c85223513b890b1376f5.html