[英]JavaScript div resizing with aspect ratio
我正在寫一個小腳本,允許用戶移動和調整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;
}
腳本有點工作。 但不幸的是,它並沒有保持寬高比完全正確。 有時,當我僅調整horizontyl時,舊的高度保持不變,有時它會起作用,但是一個長度會被調整大小並有一點偏移。
當我再次上下調整大小時,長度變得越來越平等,當它是正確的方格時,一切都是正確的。
我可以解決我的問題嗎? 我的謬誤在哪里?!
我認為你的比例是錯誤的。
您需要通過獲取舊寬度並除以新寬度或舊高度/新高度來計算此值。
例如
var ratio = newWidth / currentWidth;
newHeight = currentHeight * ratio;
如果是正在變化的高度,請更改它。
我可以做到。
非常感謝你!
我的問題是,我首先要跟蹤哪個軸有更多變化。 我沒有認識到的第二個問題是,我在舍入問題時遇到了大問題。
使用jQuery設置css大小時,它會輪詢。 我在每個事件中都采用了比率計算的高度。
這意味着不准確性變得越來越糟糕。 現在我考慮到了這一點,並找到了一種方法,使這項工作非常好。
我現在直接在onclick上執行此操作,只需更新它們而不是從元素中獲取:
currentHeight = $("#dragger").height();
currentWidth = $("#dragger").width();
再次感謝您的幫助! 這是我的最終結果: http : //jsfiddle.net/julian_weinert/xUAZ5/30/
你必須這樣做,得到最小比例(比率)。 下面的代碼是我的PHP腳本的一部分,但很容易翻譯成JS。 $iSrc
= Source和$iDest
是目標MAX寬度/高度。
你的問題是你得不到合適的比例。 定義比率的第一行是您的問題將得到解決的地方。 它獲得寬度或高度的最低比率。 你只需要寬度/高度,忘記高度/寬度。 這就是垂直縮放不正確的原因。
$scale = min($iDestWidth/$iSrcWidth, $iDestHeight/$iSrcHeight);
if($scale >= 1){
$iDestHeight = $iSrcHeight;
$iDestWidth = $iSrcWidth;
}else{
$iDestWidth = floor($scale*$iSrcWidth);
$iDestHeight = floor($scale*$iSrcHeight);
}
用以下內容替換if(比率<1)塊。 offsetx和offsety與您的(event.pageX - currentX)和(event.pageY - currentY)相關:
if (Math.abs(offsetx) > Math.abs(offsety)) {
ratio = currentHeight/currentWidth;
newHeight = currentHeight + (offsetx * ratio);
newWidth = currentWidth + offsetx;
} else {
ratio = currentWidth/currentHeight;
newHeight = currentHeight + offsety;
newWidth = currentWidth + (offsety * ratio);
}
這里是整個行動的快速解決方案: http : //jsfiddle.net/8TWRV/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.