用js更改全局css



我有一个背景图像,它位于html顶部的样式标记中。当它转到用户所在的夜间时,我想更改它。所以在白天它是图像A,在夜间它是图像B。css在标题中的原因是因为我的文件布局,否则它将无法访问图像。

如何从外部js文件更改此全局css样式?我想更改背景图像的值。任何帮助都将不胜感激。

let d;
d = new Date();
var now = d.toString().slice(16,18);
console.log(now);
if (now <= 5, now >= 20) {
console.log("it is night time")
//the code to change the image would be here
} else {
console.log("it is daytime")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Seldom Seen</title>
<link rel="stylesheet" href="css/flip.css" />
<!--the lines below here is the part i want to change-->
<style>
.bg-image{
background-image:url("images/imageA.png");
}
</style>
</head>

不确定这是否是您所要求的,但您可以使用此片段通过JavaScript:更改背景图像

document.querySelector(".bg-image").style.backgroundImage = "url(images/imageB)";

我不知道有任何方法可以使用JavaScript修改标题中的CSS,但这里有两种方法可以解决您的问题:

  1. 将其中一个背景图像分配给一个额外的类,该类通过CSS特定性覆盖原始分配
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Seldom Seen</title>
<link rel="stylesheet" href="css/flip.css" />
<!--the lines below here is the part i want to change-->
<style>
.bg-image{
background-image:url("images/imageDay.png");
}
.bg-image.night{
background-image:url("images/imageNight.png");
}
</style>
</head>
const bg = document.querySelector('.bg-image');
let d;
d = new Date();
var now = d.toString().slice(16,18);
console.log(now);
if (now <= 5, now >= 20) {
console.log("it is night time");
bg.classList.add('night');
} else {
console.log("it is daytime");
bg.classList.remove('night');
}
  1. 修改元素inline的样式属性:
if (now <= 5, now >= 20) {
document.querySelector('.bg-image').style.backgroundImage = url('./images/imageNight.jpg');
} 
else {
document.querySelector('.bg-image').style.backgroundImage = url('./images/imageDay.jpg');
}

最新更新