Owy*_*wyn 2 javascript resize image rescale
我需要调整图像的自然大小以适应屏幕,就像 Chrome 处理其中打开的图像一样,我rescale(为此编写了一个 ) 函数(如下)。
它大部分工作正常,但对于大型横向图像(例如,使用我的函数http://imageontime.com/upload/big/2013/07/20/51ea60b522bba.jpg调整大小后宽度和高度都超过屏幕)全屏图像在高度上仍然超出屏幕几行(很少在宽度上),所以我想问是否有更好的重新缩放javascript函数,或者这里是否有任何铬源专家可以研究铬源代码来调整图像大小函数,以便我可以将其移植到 JavaScript 中?
这是代码:
function setautow() {
img.style.width = 'auto';
img.style.removeProperty("height");
if (document.documentElement.clientHeight == 0) // Firefox again...
{
img.height = window.innerHeight;
}
else {
img.height = document.documentElement.clientHeight;
}
}
function setautoh() {
img.style.height = 'auto';
img.style.removeProperty("width");
if (document.documentElement.clientWidth == 0) // FF
{
img.width = window.innerWidth;
}
else {
img.width = document.documentElement.clientWidth;
}
}
function shrink(a) {
if (a) {
if (img.width != document.documentElement.clientWidth) {
setautoh();
}
}
else {
if (img.height != document.documentElement.clientHeight) {
setautow();
}
}
}
var rescaled = false;
function rescale() {
if (rescaled) {
rescaled = false;
img.height = img.naturalHeight;
img.width = img.naturalWidth;
img.style.removeProperty("height");
img.style.removeProperty("width");
}
else {
rescaled = true;
if (img.naturalWidth > img.naturalHeight) {
setautoh();
setTimeout(function () {
shrink(true);
}, 0);
}
else {
setautow();
setTimeout(function () {
shrink(false);
}, 0);
}
}
}
Run Code Online (Sandbox Code Playgroud)
只要 CSS 中未指定图像宽度/高度,下面的代码似乎就可以很好地完成这项工作。
#Javascript
window.onresize = window.onload = function()
{
resize();
}
function resize()
{
var img = document.getElementsByTagName('img')[0];
winDim = getWinDim();
img.style.height = winDim.y + "px";
if (img.offsetWidth > winDim.x)
{
img.style.height = null;
img.style.width = winDim.x + "px";
}
}
function getWinDim()
{
var body = document.documentElement || document.body;
return {
x: window.innerWidth || body.clientWidth,
y: window.innerHeight || body.clientHeight
}
}
Run Code Online (Sandbox Code Playgroud)
#CSS
body{
margin:0;
padding:0;
text-align:center;
background:rgb(51, 51, 51);
}
Run Code Online (Sandbox Code Playgroud)
#HTML
<img src="http://placehold.it/4000x3000" />
Run Code Online (Sandbox Code Playgroud)