如何使用JavaScript函数更改HTML背景?我需要一些简单的功能来将背景从一个图像更改为另一个图像?
答案 0 :(得分:4)
使用jquery
替代 IFF$("body").css("background-image", "url(/image.jpg)");
答案 1 :(得分:3)
尝试这样的事情:
function newBackGround (element,background) {
element.style.backgroundImage = "url("+background+")";
}
newBackground (myElement,"newBackground.jpg");
答案 2 :(得分:1)
非常简单:
function changeBGImage(){
document.body.background = "image.jpg";
}
希望这有助于你
<强>更新强>
或者如果您想使用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>
答案 3 :(得分:0)
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')";
}
&#13;
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
答案 4 :(得分:0)
所有这些答案都会改变身体。更改html背景的最直接方法如下:
const imagePath = "/img/sub-folder/my-image.png";
document.documentElement.style.background = `url("${imagePath}")`;
答案 5 :(得分:-1)
function changeBGImage(whichImage){
document.body.backgroundImage = "url(" + whichImage + ")";
}