JS设置元素 鼠标拖拽 且 可以以鼠标位置滚轮放大缩小
作者: qq2402398917, 支持油猴脚本定制, 爬虫
已经封装成函数了, 直接用就ok
function SetMovable(Ele)
{
let scale = 1;
let originX = 0;
let originY = 0;
let isDragging = false;
let startX, startY;
Ele.addEventListener('wheel', (event) => {
event.preventDefault();
const rect = Ele.getBoundingClientRect();
const offsetX = event.clientX - rect.left;
const offsetY = event.clientY - rect.top;
const delta = Math.sign(event.deltaY) * -0.1;
const newScale = Math.min(Math.max(0.5, scale + delta), 3);
originX = (originX - offsetX) * (newScale / scale) + offsetX;
originY = (originY - offsetY) * (newScale / scale) + offsetY;
scale = newScale;
Ele.style.transform = `translate(${originX}px, ${originY}px) scale(${scale})`;
});
Ele.addEventListener('mousedown', (event) => {
event.stopPropagation();
event.preventDefault();
isDragging = true;
startX = event.clientX;
startY = event.clientY;
Ele.style.cursor = 'grabbing';
});
Ele.onclick = event => event.stopPropagation();
window.addEventListener('mouseup', (event) => {
event.stopPropagation();
event.preventDefault();
isDragging = false;
Ele.style.cursor = 'grab';
});
window.addEventListener('mousemove', (event) => {
event.stopPropagation();
event.preventDefault();
if (!isDragging) return;
const dx = event.clientX - startX;
const dy = event.clientY - startY;
originX += dx;
originY += dy;
startX = event.clientX;
startY = event.clientY;
Ele.style.transform = `translate(${originX}px, ${originY}px) scale(${scale})`;
});
Ele.reset = function() {
scale = 1;
originX = 0;
originY = 0;
Ele.style.transform = `translate(0, 0) scale(${scale})`;
}
}