简体   繁体   English

如何使用JS动态更改BgImage

[英]How to change BgImage dynamically using JS

I was looking for a way to dynamically change the BgImage of an HTML document with JS.我正在寻找一种使用 JS 动态更改 HTML 文档的 BgImage 的方法。 I know about hardcoding the links, but I want to load it from a variable url that I provide.我知道对链接进行硬编码,但我想从我提供的可变 url 加载它。 This is what's working这是什么工作

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">Set background image</button>

<script>
function myFunction() {
  document.body.style.backgroundColor = "#f3f3f3";
  document.body.style.backgroundImage = "url('https://i.imgur.com/B95LprK.jpg')";
}
</script>

</body>
</html>

But this is what I need但这是我需要的

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">Set background image</button>

<script>
var imageLink = 'https://i.imgur.com/B95LprK.jpg'
function myFunction() {
  document.body.style.backgroundColor = "#f3f3f3";
  document.body.style.backgroundImage = "url(imageLink)";
}
</script>

</body>
</html>

Any idea on how to achieve this?关于如何实现这一目标的任何想法?

The easiest way is to use a template literal string with backticks ` ` in which you can inject variables.最简单的方法是使用带有反引号` `的模板文字字符串,您可以在其中注入变量。

var imageLink = 'https://i.imgur.com/B95LprK.jpg';
document.body.style.backgroundImage = `url(${imageLink})`;

An older way of doing it is by concatenating strings with the + operator.一种较旧的方法是使用+运算符连接字符串。

var imageLink = 'https://i.imgur.com/B95LprK.jpg';
document.body.style.backgroundImage = "url(" + imageLink + ")";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM