有没有一种方法可以使图像适合浏览器视口(viewport)?我真的很想将图像放在元素的背景中,而不是创建img标记的正常行为。那会让我在CSS中使用background-size:cover。
最佳答案
一种方法是仅使用css,并确保您的元素是块级元素,块级元素会自动占据屏幕的整个宽度。
#fullscreen
{
height: 100vh;
background-image: url("http://placehold.it/500x500");
background-repeat: no-repeat;
background-size:cover;
}
另一种解决方案是使用JavaScript,方法是将元素的宽度和高度设置为窗口的宽度和高度。
var width = window.innerWidth;
var height = window.innerHeight;
var yourEl = document.getElementById('your elements Id');
yourEl.style.height = height + 'px';
yourEl.style.width = width + 'px';
这是一个仅使用CSS的插件
http://plnkr.co/edit/yatuyJj5941hCVNmoSwD?p=preview