如何根据屏幕分辨率自适应调整背景宽高?这是一种简单易用的方法!

发布时间:2023-05-31浏览次数:0

支持注册ChatGPT Plus的OneKey虚拟卡
绑定Apple Pay、Google Pay、支付宝和微信支付进行日常消费

注册和了解更多 ->

silver

这里提供一个基于JavaScript的解决方案。

可以通过window.innerWidth和window.innerHeight来获取当前屏幕的宽度和高度,根据这两个值来调整背景的宽高。

function resizeBackground() {
  var screenWidth = window.innerWidth;
  var screenHeight = window.innerHeight;
  var background = document.getElementById("background");
  
  background.style.width = screenWidth + "px";
  background.style.height = screenHeight + "px";
}

resizeBackground();

window.addEventListener("resize", resizeBackground);

这个方法会在页面加载时、以及窗口大小变化时触发,自动改变背景的宽高。

背景的样式需要在CSS中设置,比如:

#background {
  position: fixed;
  top: 0;
  left: 0;
  background-image: url('background.jpg');
  background-size: cover;
}

其中background-size: cover属性可以使背景图片自适应屏幕大小。

字节笔记本扫描二维码查看更多内容