2015-02-11 81 views
1

我使用缩放图像以适应父级div的代码,它被称为“aspectcorrect”。 问题发生在移动版本上:我的父div具有100%宽度,并且当用户将屏幕的方向更改为横向时,图像不会调整大小以适应新div的宽度。当屏幕方向发生变化时重新运行javascript函数

当用户改变屏幕的方向时,有一种方法可以重新运行onload事件(缩放图像)?

这是我的网站:www.mcsoftware.com.br/sitemc 我仍在努力。

(要明白我在说什么,打开你的手机,当您更改屏幕方向只需点击“Continuar mesmo assim”导航)

谢谢!

aspectcorrect.js

function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) { 

    var result = { width: 0, height: 0, fScaleToTargetWidth: true }; 

    if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) { 
     return result; 
    } 

    // scale to the target width 
    var scaleX1 = targetwidth; 
    var scaleY1 = (srcheight * targetwidth)/srcwidth; 

    // scale to the target height 
    var scaleX2 = (srcwidth * targetheight)/srcheight; 
    var scaleY2 = targetheight; 

    // now figure out which one we should use 
    var fScaleOnWidth = (scaleX2 > targetwidth); 
    if (fScaleOnWidth) { 
     fScaleOnWidth = fLetterBox; 
    } 
    else { 
     fScaleOnWidth = !fLetterBox; 
    } 

    if (fScaleOnWidth) { 
     result.width = Math.floor(scaleX1); 
     result.height = Math.floor(scaleY1); 
     result.fScaleToTargetWidth = true; 
    } 
    else { 
     result.width = Math.floor(scaleX2); 
     result.height = Math.floor(scaleY2); 
     result.fScaleToTargetWidth = false; 
    } 
    result.targetleft = Math.floor((targetwidth - result.width)/2); 
    result.targettop = Math.floor((targetheight - result.height)/2); 

    return result; 
} 

onimageload.js

function OnImageLoad(evt) { 

    var img = evt.currentTarget; 

    // what's the size of this image and it's parent 
    var w = $(img).width(); 
    var h = $(img).height(); 
    var tw = $(img).parent().width(); 
    var th = $(img).parent().height(); 

    // compute the new size and offsets 
    var result = ScaleImage(w, h, tw, th, false); 

    // adjust the image coordinates and size 
    img.width = result.width; 
    img.height = result.height; 
    $(img).css("left", result.targetleft); 
    $(img).css("top", result.targettop); 
} 

哪里的onload功能发生

<img onload="OnImageLoad(event);" /> 

https://jsfiddle.net/ffxeqq21/

+0

请提供任何相关的代码,以您的问题。 – 2015-02-11 14:52:41

+0

只是再次检查帖子,现在有更多的信息.​​.. – 2015-02-12 14:25:42

回答

0

你可以尝试一些Ĵ像jQuery mobile avascript库,并使用orientationchange event这样,你可能只是做

$(window).on("orientationchange", function(event) { 
    //Some code 
}); 
+0

感谢您的回答,但哪些代码?现在有更多关于我的帖子的信息,请检查一下。 :) – 2015-02-12 14:26:54

+0

我想我需要在img标签上重新运行onload事件。 对不对?但是,我如何在你提供给我的代码中插入它? – 2015-02-12 14:34:40

+0

它说'//一些代码'把你的代码(简单的调用你的函数)。你需要首先包含jQuery Mobile(链接在我的答案上)。 还记得使用'$(document).ready(function(){});' – 2015-02-12 14:58:22

相关问题