图像resize以适应屏幕

考虑到导航栏的可用空间,我创建了此代码以调整照片/图像的大小以适应屏幕。

该脚本将在图像加载和导航点击时触发。

有没有人建议改善这一点并确保浏览器兼容性?

HTML

$(document).ready(function(){ $("#photo").load(function(){ resize(); }); $(".navigation img").click(function(){ var imgPath = $(this).attr("src"); $("#photo").attr({ src: imgPath }); resize(); return false; }); }); 

使用Javascript

 resize = function() { var borderVt=150; //value based on css style. bottom bar + padding of photoContain var borderHz=40; //value based on css style photoContain padding $("#photo").css("width", "auto").css("height", "auto"); // Remove existing CSS $("#photo").removeAttr("width").removeAttr("height"); // Remove HTML attributes var origSizeW = $("#photo").width(); var origSizeH = $("#photo").height(); var ratioVt=(origSizeW/origSizeH); var ratioHz=(origSizeH/origSizeW); var winW = $(window).width(); var winH = $(window).height(); var screenSizeW=Math.round(winW-borderHz); var screenSizeH=Math.round(winH-borderVt); if (origSizeW>=origSizeH){ var newHeight = Math.round(screenSizeW*ratioHz); if (newHeight <= screenSizeH){ $("#photo").css("width", screenSizeW); // Set new width $("#photo").css("height", newHeight); } else{ $("#photo").css("height", screenSizeH); } } else{ $("#photo").css("height", screenSizeH); // Set new height } }; 

我知道这个问题已经过时了,但这里有一个解决方案(虽然我确信OP的工作正常):

这个jQuery插件似乎完全符合您的需求: http : //code.google.com/p/jquery-imagefit-plugin/

如果你在100%高度,100%宽度元素上执行它: http : //www.tutwow.com/htmlcss/quick-tip-css-100-height/

   

(演示: http : //jsfiddle.net/nottrobin/9Pbdz/ )

尝试使用jQuery-Backgrounder插件 。 您可以调整它来做您需要的事情。 这是一个例子:

   [...] 
Birthday party

我写了一个插件!

 jQuery.fn.positionMe = function () { var oH = $(window).height(); var oW = $(window).width(); var iH = this.outerHeight(); var iW = this.outerWidth(); // When the image is too small so, do nothing if(iW>oW && iH>oH){ // Otherwise, proportionate the image relative // to its container if(oH/iH > oW/iW){ this.css("width", oW); this.css("height", iH*(oW/iW)) } else { this.css("height", oH); this.css("width", iW*(oH/iH)); } } return this; } 

用法:

 $("#photo").positionMe(); 

我是这样做的:

  jQuery(document).ready(function($) { $('.wp-post-image').height($(window).height()); }); 

看起来不错,但我建议将resize函数附加到jQuery的Window Resize Event处理程序。 然后图像将随页面拉伸和缩小。

 var w=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||document.body.offsetWidth||window.screen.availWidth; var h=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||document.body.offsetHeight||window.screen.availHeight; function resize() { a=document.getElementsByClassName(' scale'); for(var i=0; i=1.5){ aW=w; aH=w-(w*(34/100)); mT=(aH/2)*-1; mL=(aW/2)*-1; } else { aH=h; aW=h+(h*(66/100)); mT=(aH/2)*-1; mL=(aW/2)*-1; } a[i].style.height=aH+'px'; a[i].style.width=aW+'px'; a[i].style.marginTop=mT+'px'; a[i].style.marginLeft=mL+'px'; } }