2015-02-11 61 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