Javascript 将图像适配到视口
我需要使图像适合视口/窗口大小 我使用以下代码来执行此操作:Javascript 将图像适配到视口,javascript,jquery,events,viewport,image-scaling,Javascript,Jquery,Events,Viewport,Image Scaling,我需要使图像适合视口/窗口大小 我使用以下代码来执行此操作: $(".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 = ($(windo
$(".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"
});
});
$(.fittedmg”)。每个(函数(){
//我想限制大小,并在非常小的视口上显示滚动条
高度=($(窗口).height()<725)?725:$(窗口).height();
宽度=($(窗口).width()<1150)?1150:$(窗口).width();
var newWidth,newHeight;
$(本)
.removeAttr(“高度”)
.removeAttr(“宽度”);//重置img大小
//计算尺寸并保留它
如果($(this.width()/width)>($(this.height()/height)){
新高度=高度;
newWidth=height/($(this.height()/$(this.width());
}否则{
newHeight=width/($(this.width()/$(this.height());
新宽度=宽度;
};
$(此)。停止(真、假)。设置动画({
“高度”:新高度+像素,
“宽度”:新宽度+“px”
});
});
我将代码包装在一个函数中,我在resize和$('.fittedImg').load()和$('.fittedImg').ready()等事件中调用该函数
结果很奇怪:
在Chrome中,它正常工作,但有时图像会在反复刷新时拉伸。在IE上也有同样的问题。Opera永远不会失败,safari完全忽略了计算(一直在拉伸)
我的计算和/或事件调用有什么问题
多谢各位
窗口
)中,以下是一些可能有用的简单计算。概念非常简单,基于包含度量和图像度量,计算一个比率。然后将其与原始度量值相乘:
$(".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');
}
});
1.我怎么做?load()和ready()不够好吗?2.没用。把我的例子当作样板吧
.load()
应该足以获得宽度/高度,但您可以在处理程序中控制台值以确保。