图像自适应调整大小+Javascript的问题
Problems with image adaptive resizing + Javascript
大家晚上好!!
我正面临着一些图像调整大小的问题;Javascript。
我写了一个函数来调整图像的大小,保持纵横比。功能如下:
function computeRatio () {
var el_image = document.getElementById("div_image");
var newImg = new Image();
newImg.src = document.getElementById("image").src;
// GET IMAGE REAL DIMENSIONS
var image_height = newImg.height;
var image_width = newImg.width;
// SET WINDOW DIMENSIONS
var window_height = 762;
var window_width = 600;
// COMPUTE DIMENSION RATIOS
var height_ratio = image_height / window_height;
var width_ratio = image_width / window_width;
// RESET IMAGE POSITION
el_image.style.left = "0px";
el_image.style.top = "0px";
if (height_ratio > width_ratio) {
var width = window_height/(image_height/image_width);
// SET NEW DIMENSIONS (MAX HEIGHT & NEW WIDTH)
el_image.style.width = width+"px";
el_image.style.height = window_height+"px"
// SET NEW POSITION TO CENTER IMAGE
var scroll_x = (window_width-width)/2;
el_image.style.left = scroll_x+"px";
} else {
var height = window_width*(image_height/image_width);
// SET NEW DIMENSIONS (MAX WIDTH & NEW HEIGHT)
el_image.style.width = window_width+"px"
el_image.style.height = height+"px";
var scroll_y = (window_height-height)/2;
el_image.style.top = scroll_y+"px";
}
}
这是HTML:中的相关部分
<div id="div_image" style="display: block;">
<img src="" alt="0" id="image" onLoad="computeRatio ()"/>
</div>
除了处理不太小的图像(即大小>1MB)外,它的工作非常好。
当这种情况发生时,函数会计算正确的尺寸,但随后图像会以全屏显示(W=600px,H=762px),显然,它没有居中!
我真的不明白为什么会发生这种事!!
有什么帮助吗?
感谢所有
要保持容器中图像的纵横比,只需将图像设置为display:block
并添加width:100%
即可。效果是图像将填充到包含元素的宽度,并且高度将自动调整。
#image {
display:block;
width:100%;
}
相关文章:
- javascript问题正文样式
- 将代码放入click函数时出现javascript问题
- 奇怪的javascript问题
- 选中复选框的Jquery/Javascript问题使用输入框操作将行从一个表添加到另一个表
- 多上传的JavaScript问题
- 使用YouTube iFrame API的IE中的JavaScript问题
- 关于函数的Javascript问题 - IIFE
- Javascript问题与下拉菜单上的单击事件有关
- JavaScript 问题 - 意外的令牌 (.
- Chrome 中的 JavaScript 问题
- 在javascript问题中应用复合css规则
- Javascript问题,flexslider脚本未加载
- document.write和document.innerHTML以及其他javascript问题之间有什么区别
- jQuery到纯javaScript问题
- javascript问题后的onblur和onfocus
- 谷歌地图API和JavaScript问题:-(
- 第三方javascript问题
- javascript问题中的全局变量
- 嵌套if的javascript问题
- 绑定的Javascript问题