这是一种方法。这不是很棒,但有效。 http://jsfiddle.net/78Lvc/11/
我将图像标签更改为如下所示:
<img src="http://fitzgeraldmedia.net/images/range1.jpg" id="img" imgWidth="467" imgHeight="700" onload="fixMyWidth()"/>
您会注意到我添加了一些属性和一个onload
. 您必须在代码中或手动添加属性。之所以需要高度和宽度,是因为需要知道图像的高度来计算 JS 中所需的空间。
然后内联,我有这个代码:
<script>
//get the width of the browser right now
var containerWidth = document.body.offsetWidth;
//get the attributes that we have specified for this image
var imgWidth = document.getElementById("img").getAttribute("imgWidth");
var imgHeight = document.getElementById("img").getAttribute("imgHeight");
//since the img is to be 50% of the container width
var widthRatio = containerWidth / imgWidth / 2 ;
//now set the height of the image
document.getElementById("img").style.height = (imgHeight * widthRatio) + "px";
//once the image has actually loaded, run this
function fixMyWidth(){
//this will make it 'responsive' again
document.getElementById("img").style.height = "";
document.getElementById("img").style.width = "";
}
</script>