如何在不使用CSS的情况下居中动态切换的背景图片?
动态切换背景图片并居中显示的实现方案
问题修正与核心说明
- HTML标签错误修复:你在
<body>标签里重复声明了class属性,这不符合HTML规范,正确写法是单个class属性包含多个类(不过你的JS会直接覆盖className值,所以初始只需设置一个类即可):
<body class="day"></body>
- 背景居中的实现逻辑:HTML原生没有直接控制背景图片居中的属性,必须借助CSS实现背景定位——所谓“不借助CSS”是对HTML功能的误解,背景样式本身属于CSS的范畴。你需要在切换的类中添加背景定位、重复和尺寸控制属性,确保图片居中且适配屏幕:
.day { background-image: url("https://material.angular.io/assets/img/examples/shiba2.jpg"); background-position: center center; background-repeat: no-repeat; background-size: cover; min-height: 100vh; margin: 0; } .night { background-image: url("https://picsum.photos/300/200.jpg"); background-position: center center; background-repeat: no-repeat; background-size: cover; min-height: 100vh; margin: 0; }
- 关于div和center标签的误区:
<center>标签仅能让内部元素的位置居中,无法控制背景图片的显示位置;用div包裹也无法直接实现背景居中,这两种方式都不适用你的需求。
完整可运行代码
<!DOCTYPE html> <html> <head> <style> .day { background-image: url("https://material.angular.io/assets/img/examples/shiba2.jpg"); background-position: center center; background-repeat: no-repeat; background-size: cover; min-height: 100vh; margin: 0; } .night { background-image: url("https://picsum.photos/300/200.jpg"); background-position: center center; background-repeat: no-repeat; background-size: cover; min-height: 100vh; margin: 0; } </style> </head> <body class="day"> <script> setInterval(change_background, 1000 * 60 * 1); function change_background() { var d = new Date(); var n = d.getHours(); console.log(n); if (n == 19 || n < 7) { document.body.className = "night"; } else { document.body.className = "day"; } console.log("test"); } change_background(); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Hajar Ali
相关产品推荐
相关产品推荐

