我正在调用一个API,该API返回图像的URL,该图像可以是任何大小,并且是完全随机的。
我正在尝试调整图像的大小以适合页面,以确保内容不被压到折叠之下,或者图像不会碰到页面的宽度。
我在下面写了一些Javascript,已经对其进行了测试,并且得到了一些奇怪的结果-控制台日志说图像是一种尺寸,但是Chrome开发工具中的元素选择器通常说的完全不同。如果您可以看一下,那肯定会在代码中犯一些基本错误。
Javascript设置视口的高度和宽度,检查是否有照片src。加载图像后,它将检查自然尺寸是否大于视口的自然尺寸,如果是,则尝试调整其大小-这是脚本失败的地方。
//check viewport
var viewportWidth = getWidth();
var viewportHeight = getHeight();
//get the media
if (data[2] == "photo") {
var tweetImage = document.getElementById("tweetImage");
//when it loads check the size against the browser size
tweetImage.onload = function () {
console.log('image height: ' + tweetImage.naturalHeight);
console.log('viewport height: ' + viewportHeight);
//does it matter if its landscape?
if (viewportWidth - tweetImage.naturalWidth < 1) {
tweetImage.width = Math.floor(tweetImage.naturalWidth - (viewportWidth - tweetImage.naturalWidth) * 1.2);
console.log('w');
} else if (Math.floor(viewportHeight - tweetImage.naturalHeight) < 1) {
console.log('h');
console.log(viewportHeight - tweetImage.naturalHeight);
console.log('changed result: ' + Math.floor(tweetImage.naturalHeight - (Math.abs(viewportHeight - tweetImage.naturalHeight))));
tweetImage.height = Math.floor(tweetImage.naturalHeight - (Math.abs(viewportHeight - tweetImage.naturalHeight)*1.2));
} else {
tweetImage.height = Math.floor(viewportHeight / 2);
}
tweetImage.align = "center";
tweetImage.paddingBottom = "10px";
};
//tweetImage.height = Math.floor(viewportHeight / 2);
tweetImage.src = data[3];
}
最佳答案
一种选择是使用基于CSS的解决方案,例如视口高度单位。
.example {
height: 50vh; // 50% of viewport height
}
见http://web-design-weekly.com/2014/11/18/viewport-units-vw-vh-vmin-vmax/