繁体   English   中英

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

[英]Resize images with Javascript to fit them within the viewport

我正在调用将图像返回URL的API,该图像可以是任何大小,并且是完全随机的。

我正在尝试调整图像的大小以适合页面,以确保内容不被压到折叠之下,或者图像不会碰到页面的宽度。

我在下面写了一些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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM