gpt4 book ai didi

javascript - 如何使脚本在窗口调整大小和方向更改时调整图像和 div 的大小

转载 作者:行者123 更新时间:2023-11-28 06:24:14 27 4
gpt4 key购买 nike

我目前正在使用以下 javascript 将图像的大小调整为其父级的大小,同时保持纵横比并保持父级 div 为正方形。所以我有一个方框,矩形框根据方向拉伸(stretch)到最大宽度或最大高度。这在第一次加载时效果很好,但是我无法让图像和 div 在页面方向更改时调整大小或调整大小以工作。有任何想法吗。我已经尝试使用 window.resizewindow.orientation 监听器。

原始代码来自: Scale, crop, and center an image...

var aspHt = $('.aspectcorrect').outerWidth();
$('.aspectcorrect').css('height', aspHt + 'px').css('width', aspHt + 'px');

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

function RememberOriginalSize(img) {
if (!img.originalsize) {
img.originalsize = {
width : img.width,
height : img.height
};
}
}

function FixImage(fLetterBox, div, img) {

RememberOriginalSize(img);

var targetwidth = $(div).width();
var targetheight = $(div).height();
var srcwidth = img.originalsize.width;
var srcheight = img.originalsize.height;
var result = ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox);

img.width = result.width;
img.height = result.height;
$(img).css("left", result.targetleft);
$(img).css("top", result.targettop);
}

function FixImages(fLetterBox) {
$("div.aspectcorrect").each(function(index, div) {
var img = $(this).find("img").get(0);
FixImage(fLetterBox, this, img);
});
}

window.onload = function() {
FixImages(true);
};

最佳答案

在 $(window).resize() 之后调用 .resize():

$(window).resize( function(){

var height = $(window).height();
var width = $(window).width();

if(width>height) {
// Landscape
$("#landscape").css('display','none');
} else {
// Portrait
$("#landscape").css('display','block');
$("#landscape").click(function(){
$(this).hide();
});
}
}).resize();

关于javascript - 如何使脚本在窗口调整大小和方向更改时调整图像和 div 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35376812/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com