我正在编写一个小脚本,允许用户移动 div 并调整其大小。我需要保持宽高比,但我的逻辑不起作用。
function resizing() {
var currentHeight = elmnt.offsetHeight;
var currentWidth = elmnt.offsetWidth;
var newHeight = currentHeight + (event.pageY - currentY);
var newWidth = currentWidth + (event.pageX - currentX);
var ratio = currentWidth / currentHeight;
if(ratio < 1) {
newwidth = parseInt(newHeight * ratio);
}
else {
newheight = parseInt(newWidth / ratio);
}
elmnt.style.height = newHeight + "px";
elmnt.style.width = newWidth + "px";
currentY = event.pageY;
currentX = event.pageX;
}
脚本可以正常工作。但不幸的是,它并不能保持纵横比完全正确。有时,当我仅调整水平大小时,旧高度保持不变,有时它可以工作,但一个长度会调整大小并有一点偏移。
当我上下调整大小时,长度变得越来越相等,当它是一个适当的正方形时,一切都是正确的。
我怎样才能解决我的问题?我的谬误在哪里?!
最佳答案
我认为你的比例是错误的。
您需要通过旧宽度除以新宽度或旧高度/新高度来计算。
例如
var ratio = newWidth / currentWidth;
newHeight = currentHeight * ratio;
如果高度发生变化,请更改它。
关于JavaScript div 根据宽高比调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14611736/