JavaScript div使用宽高比调整大小 [英] JavaScript div resizing with aspect ratio

查看:254
本文介绍了JavaScript div使用宽高比调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个小脚本,允许用户移动和调整div的大小.我需要保持宽高比,但逻辑不起作用.

I'm writing a little script that allows the user to move and resize a div. I need to keep the aspect ratio and my logic doesn't work.

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;
}

脚本的工作原理.但是不幸的是,它不能使宽高比完全正确.有时,当我仅调整地平线尺寸时,旧高度保持不变,有时仍然有效,但是在调整长度时会稍有偏移.

The script kind of works. But unfortunately it doesn't keep the aspect ratio completely correct. Sometimes, when I resize horizontyl only, the old height remains the same, sometimes it works, but one length gets resized with a little offset.

当我上下调整大小时,长度变得越来越相等,当它是适当的正方形时,一切都正确了.

When I resize up and down and up and down again, the lengths gets more and more equal and when it is a proper square, everything is right.

我可以解决我的问题吗?我的谬论在哪里?!

Hwo can I fix my problems? Where is my fallacy?!

推荐答案

我可以解决这个问题.

非常感谢!

我的问题是,我首先必须跟踪哪个轴的变化更大.我不认识的第二个问题是,我在四舍五入问题上遇到了 BIG 问题.

My problem was that I first, had to track of which axis has more change. The second problem, which I didn't recognized was, that I had BIG problems with rounding issues.

使用jQuery设置CSS大小时,它会四舍五入.而且我把每个事件的比率都用来计算比率.

When setting the css size using jQuery, it rounds. And I took the height for ratio calculations every single event.

这意味着不准确性越来越严重. 现在,我考虑了这一点,并想出了一种使此功能非常好很好的方法.

That means that the inaccuracy was getting more and more bad. Now I took this into account and figured out a way to get this working very good.

我现在直接在click上执行此操作,只需更新它们即可,而不是从元素中获取:

I now do this directly onclick and just update them instead of getting from the element:

currentHeight = $("#dragger").height();
currentWidth = $("#dragger").width();

因此,再次感谢您的帮助!这是我的最终结果: http://jsfiddle.net/julian_weinert/xUAZ5/30/

So thanks again for your help! Here is my final result: http://jsfiddle.net/julian_weinert/xUAZ5/30/

这篇关于JavaScript div使用宽高比调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆