如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:10:15  来源:igfitidea点击:

How to change HTML background with JavaScript Function?

javascripthtmlimagebackground

提问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 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 + ")";
}