开发者

Maintain aspect ratio on browser window resize?

I have a simple page with images, and when the user clicks the image, it opens up a new browser window with the image filling the area. I have the css set on the new window so that the image height and width are both 100% (and overflow is set to hidden) so that the window can be resized.

But what I need is for the window to maintain aspect ratio if the user resizes it. Right now, I'm stuck because I'm not getting how the event works, but I think I'm making this harder than it needs to be. Right now I have:

$(function(){
    $(window).resize(function() {
        var height = $(this).attr("innerHeight");
        var width = $(this).attr("innerWidth");
        if(height/width != .75){
            window.resizeTo(width,width*.75);
        }
    });
});

Before I added the conditi开发者_运维知识库onal, the window would immediately start shrinking (apparently opening a new window fires the resize event). Adding the conditional preventing this from happening when the window opens, but any resizing starts the shrinking again.

Is it just because the height and width are never exactly the right ratio (should I manually set the width to a round number ever time) or is there something else I'm doing wrong? Or is there some other way to get what I'm after that's more straightforward?


I believe you're on the right track, but resizeTo() resizes the entire browser window, including window frames, toolbars, menus, etc.

So, when you call resizeTo(), it fires, detects the inner height/width isn't the desired aspect ratio, and resizes the entire window, frames and toolbars and all.

This then fires resizeTo() again, which finds, again, the inner aspect ratio isn't right, and so keeps firing and resizing ad infinitum.

To fix this, you'd need to:

  1. Detect the outer size by resizing and then testing the innerWidth/innerHeight. Remember, this can change as the user works with their browser.
  2. Call resizeTo with a size that accounts for the outer chrome and achieves the desired aspect ratio for the innerWidth/inner Height.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜