当我单击按钮并进行平滑过渡时,我正在尝试更改网站的背景。我知道这需要预加载,但是我不确定如何执行此操作。
transition: background-image 3s linear;
js
document.getElementById("loadBG").onclick = function () {
let randomInt = Math.floor(Math.random() * (100 - 1) + 1);
document.getElementById(
"main"
).style.backgroundImage = `url(https://source.unsplash.com/1920x1080/?finland?sig=${randomInt})`;
};
您要应用的background-image
属性无效。同样,您尝试应用的nextImage.src
来源属性也无效。
有关详细信息,请参见代码段注释。
如果您要做的只是应用background-image
属性,则无需创建图像节点。也可以优化Math.random()
方法(不是必需的,只是一个nitpick)。
原始代码(带有console.log反馈)和有效版本已包含在下面的代码片段中:
document.getElementById("loadBG-error").onclick = function() {
const nextImage = new Image();
nextImage.src = `url("https://source.unsplash.com/1920x1080/?finland?sig=${Math.random()}")`;
setTimeout(function() {
document.getElementById("main").style.backgroundImage = nextImage.src;
}, 3000);
console.log('incorrect background-image property url:',nextImage.src);
};
/*
This happens because the image node's (nextImage) src attribute is being
declared with a background-image css property, it starts with "url(... )",
when you have a filepath that doesn't start with a protocol (https://)
the browser will assume it's relative and prepend the current site's domain
to the url, e.g: "https://stacksnippets.net/url(...)".
In addition, the double apostrophes in that string are being ASCII encoded to "%22".
*/
document.getElementById("loadBG-fix").onclick = function() {
let randomInt = Math.floor(Math.random() * (100 - 1) + 1);
setTimeout(function() {
document.getElementById("main").style.backgroundImage = `url(https://source.unsplash.com/1920x1080/?finland?sig=${randomInt})`;
}, 500);
};
/*
If you just need to declare a background-image property for an existing element,
there is no need to create an image node first.
The Math.random() method can be further improved to return a set range(1)
with no floating point value (decimal)(2)
(1) Math.random() * (max - min) + min
(2) Math.floor()
*/
#main {
height: 300px;
width: 100%;
}
<div id="main"></div>
<button id="loadBG-error">Load BG (see error)</button>
<hr>
<button id="loadBG-fix">Load BG (apply fix)</button>
为了将图像加载为backgorund图像,其所在的容器必须具有特定的高度和宽度。我为#主div设置了高度和宽度。
并且您不需要像新图像这样的定义(如果您没有其他目的使用新图像),因为img和背景url图像中的src彼此不同。你甚至不能做到这两个。因为它们的工作方式不同。
document.getElementById("loadBG").onclick = function() {
let url = `url("https://source.unsplash.com/1920x1080/?finland?sig=${Math.random()}")`;
setTimeout(function() {
document.getElementById("main").style.backgroundImage = url;
console.log("work")
}, 1000);
};
#main {
width: 100%;
height: 400px;
background-position: center;
background-size: cover;
}
<button type="button" id="loadBG">Click me</button>
<div id="main"></div>