例如我定了WIDTH是500PX,我只能向500PX以下的縮小,不能拉大,請問怎樣用RESIZE把他拉大。
(function() {
"use strict";
// horizontal direction
(function resizableX() {
const resizer = document.querySelector(".resizer-x");
resizer.addEventListener("mousedown", onmousedown);
resizer.addEventListener("touchstart", ontouchstart);
// for mobile
function ontouchstart(e) {
e.preventDefault();
resizer.addEventListener("touchmove", ontouchmove);
resizer.addEventListener("touchend", ontouchend);
}
function ontouchmove(e) {
e.preventDefault();
const clientX = e.touches[0].clientX;
const deltaX = clientX - (resizer._clientX || clientX);
resizer._clientX = clientX;
const l = resizer.previousElementSibling;
const r = resizer.nextElementSibling;
// LEFT
if (deltaX < 0) {
const w = Math.round(parseInt(getComputedStyle(l).width) + deltaX);
l.style.flex = `0 ${w < 10 ? 0 : w}px`;
r.style.flex = "1 0";
}
// RIGHT
if (deltaX > 0) {
const w = Math.round(parseInt(getComputedStyle(r).width) - deltaX);
r.style.flex = `0 ${w < 10 ? 0 : w}px`;
l.style.flex = "1 0";
}
}
function ontouchend(e) {
e.preventDefault();
resizer.removeEventListener("touchmove", ontouchmove);
resizer.removeEventListener("touchend", ontouchend);
delete e._clientX;
}
// for desktop
function onmousedown(e) {
e.preventDefault();
document.addEventListener("mousemove", onmousemove);
document.addEventListener("mouseup", onmouseup);
}
不建議使用觸控裝置來調整元素的寬高。
如果不需要縱向調整,將 y
和 height
刪除即可。
<div class="box">
<span class="resizer"></span>
</div>
.box {
width: 300px;
height: 200px;
position: relative;
background-color: cyan;
}
.box .resizer {
width: 10px;
height: 10px;
position: absolute;
right: 0;
bottom: 0;
background-color: blue;
cursor: se-resize;
}
const doc = document.querySelector('html');
const resizer = document.querySelector('.resizer');
const cursor = {
x: 0,
y: 0,
width: 0,
height: 0,
target: null,
dragging: false
};
doc.addEventListener('mousedown', grab);
doc.addEventListener('mousemove', drag);
doc.addEventListener('mouseup', release);
function grab(e) {
if (e.button !== 0 || e.target !== resizer) return;
const target = cursor.target = resizer.closest('.box');
const cStyle = window.getComputedStyle(target);
cursor.x = e.clientX;
cursor.y = e.clientY;
cursor.width = Number(cStyle.width.slice(0, -2));
cursor.height = Number(cStyle.height.slice(0, -2));
cursor.dragging = true;
}
function drag(e) {
if (!cursor.dragging) return;
cursor.target.style.width = `${cursor.width + e.clientX - cursor.x}px`;
cursor.target.style.height = `${cursor.height + e.clientY - cursor.y}px`;
}
function release(e) {
cursor.dragging = !cursor.dragging ? true : false;
}