使用Javascript调整图像大小以使其适合视口

时间:2015-02-20 07:59:22

标签: javascript html css image

我正在调用一个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];

            }

1 个答案:

答案 0 :(得分:1)

一种选择是使用基于CSS的解决方案,如视口高度单位。

.example {
    height: 50vh; // 50% of viewport height
}

请参阅http://web-design-weekly.com/2014/11/18/viewport-units-vw-vh-vmin-vmax/

相关问题