簡體   English   中英

使圖像適合視口

[英]Fit images to viewport

我需要將圖像適合視口/窗口大小。

我用這段代碼來做:

$(".fittedImg").each(function () {

        // I want to limit the size, and show a scrollbar on very small viewport
        height  = ($(window).height() < 725) ? 725 : $(window).height();
        width   = ($(window).width() < 1150) ? 1150 : $(window).width();

        var newWidth, newHeight;
        $(this)
            .removeAttr("height")
            .removeAttr("width"); // reset img size

        // calculate dimension and keep it 
        if (($(this).width() / width) > ($(this).height() / height)) {
            newHeight = height;
            newWidth = height / ($(this).height() / $(this).width());

        } else {
            newHeight = width / ($(this).width() / $(this).height());
            newWidth = width;
        };
        $(this).stop(true, false).animate({
            "height": newHeight + "px",
            "width": newWidth + "px"
        });
});

我將該代碼包裝在我調用resize的函數中,以及諸如$('。fitsImg')。load()和$('。fitsImg')。ready()之類的事件中。

結果非常奇怪:在Chrome中它通常可以正常工作,但有時圖像會在重復刷新時延伸。 在IE上存在完全相同的問題。 Opera永遠不會失敗,safari會忽略計算(永遠不會拉伸)。

我的計算和/或事件調用有什么問題?

謝謝。

  1. 提取寬度/高度之前,請確保圖像已完全加載
  2. 在計算之前不要刪除寬度/高度屬性

假設您想要將圖像放入包含元素(在本例中為window )中,這里有一些您可能會覺得有用的更簡單的計算。 這個概念很簡單,基於包含度量和圖像測量,計算比率。 然后將其與原始度量相乘:

$(".fittedImg").load(function(){

  var imgWidth = this.width,
      imgHeight = this.height,
      winWidth = $(window).height(),
      winHeight = $(window).width(),
      ratio = Math.min(winWidth/imgWidth, winHeight/imgHeight);

   // if you don’t want it to upscale, use Math.min or Math.max on the ratio

   $(this).stop(true, false).animate({
       height: imgHeight*ratio,
       width: imgWidth*ratio
   });
});

請注意,某些擴展程序(如AdBlock)可能會破壞圖像中提取的寬度/高度。 您可以控制和imgWidth / imgHeight文本,以確保它可用。

另請注意,添加此事件后,您的圖片可能已加載,具體取決於您放置代碼的方式。 在這種情況下,您應該檢查IMG元素上的complete屬性:

$('fittedImg').each(function() {
    $(this).load(function() {
        // the calculations goes here
    });
    if (this.complete) { // check if image is already loaded
        $(this).trigger('load');
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM