方法一:设置图片为div的背景图片,div默认宽度等于body,设置div高度与body一致,bgs为cover,图片始终铺满div
**[background-size]规定背景图片的尺寸 cover contain 百分比 px
**[background-origin]规定背景图片的定位区域
**[background-clip]规定背景图片的绘制区域 border-box /content-box
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
div {
position: absolute;
top: 0;
left: 0;
width: 100%;
min-height: 100%;
height: auto;
background-image: url('./4444.jpg');
background-size: cover;
}
</style>
</head>
<body>
<div class="div"></div>
</body>
<script>
</script>
</html>
方法二:JS监听浏览器尺寸变化,赋值给元素
<style>
* {
margin: 0;
padding: 0;
height: 100%;
}
p {
background-image: url('./4444.jpg');
background-size: cover;
}
</style>
<body>
<p id="img"></p>
</body>
<script>
window.addEventListener('load', function () {
window.οnresize = function () {
console.log(444);
//获取浏览器窗口高度
var winHeight = 0;
if (window.innerHeight) {
winHeight = window.innerHeight;
// document.body是body,document.documentElement是html
} else if ((document.body) && (document.body.clientHeight))
winHeight = document.body.clientHeight;
//通过深入Document内部对body进行检测,获取浏览器窗口高度
if (document.documentElement && document.documentElement.clientHeight)
winHeight = document.documentElement.clientHeight;
//P高度为浏览器窗口的高度
document.getElementById("img").style.height = winHeight + "px";
}
})
</script>