如何使用 JavaScript 函数更改 HTML 背景?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2618699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change HTML background with JavaScript Function?
提问by Rella
How to change HTML background with JavaScript Function? I need some simple function to change background from one image to another?
如何使用 JavaScript 函数更改 HTML 背景?我需要一些简单的功能来将背景从一张图片更改为另一张图片吗?
采纳答案by Marcos Placona
Very simple like this:
非常简单像这样:
function changeBGImage(){
document.body.background = "image.jpg";
}
Hope this helps you
希望这对你有帮助
UPDATE
更新
Or if you wanna use CSS (more elegant solution) with it, you could use:
或者,如果您想使用 CSS(更优雅的解决方案),您可以使用:
<style>
.bg1 {
background-image: url(images/my_image.jpg);
}
</style>
<body id="page_body">
<script>
function changeBGImage(whichImage){
document.getElementById('page_body').className="bg"+whichImage;
}
</script>
回答by David
An alternative IFFusing jquery
使用 jquery的替代IFF
$("body").css("background-image", "url(/image.jpg)");
回答by Jeff Fohl
Try something like this:
尝试这样的事情:
function newBackGround (element,background) {
element.style.backgroundImage = "url("+background+")";
}
newBackground (myElement,"newBackground.jpg");
回答by xgqfrms
demo codes:
演示代码:
element = document.querySelector("body");
element.style.backgroundImage = "url('https://cdn.xgqfrms.xyz/logo/logo.png')";
elements = document.querySelectorAll("div");
for(let element of elements){
element.style.background = "url('https://cdn.xgqfrms.xyz/logo/logo.png')";
}
reference links:
参考链接:
http://www.w3schools.com/jsref/dom_obj_style.asphttp://www.w3schools.com/jsref/prop_style_background.asphttp://www.w3schools.com/jsref/prop_html_style.asphttp://www.w3schools.com/jsref/met_document_queryselectorall.asphttp://www.w3schools.com/jsref/met_document_queryselector.asphttps://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAllhttps://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll
http://www.w3schools.com/jsref/dom_obj_style.asp http://www.w3schools.com/jsref/prop_style_background.asp http://www.w3schools.com/jsref/prop_html_style.asp http://www .w3schools.com/jsref/met_document_queryselectorall.asp http://www.w3schools.com/jsref/met_document_queryselector.asp https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll https: //developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll
回答by Seph Reed
All of these answers change the body. The most direct way to change the html background is like so:
所有这些答案都会改变身体。最直接的改变html背景的方法是这样的:
const imagePath = "/img/sub-folder/my-image.png";
document.documentElement.style.background = `url("${imagePath}")`;
回答by Harmen
function changeBGImage(whichImage){
document.body.style.backgroundImage = "url(" + whichImage + ")";
}

