如何使用JavaScript更改div的背景图像?

42

这是我的代码

<div style="text-align:center;">
  <div class="ghor" id="a" onclick="chek_mark()"></div>
  function call
</div>
<script type="text/javascript">
  function chek_mark(){
   var el= document.getElementById("a").style.background-image;
   if (el.url("Black-Wallpaper.jpg"))  
   {
     el.url = "cross1.png";
    }
    else if(el.url("cross1.png"))
    {
      alert("<h1>This is working too.</h1>");
     }
   }
</script>

我想使用if else条件语句更改背景图片。

this is the style-sheet
.ghor //this is the div class
{
    background-image: url('Black-Wallpaper.jpg');
    background-size: cover;
    border-radius: 5px;
    height: 100px;
    width: 100px;
    box-shadow: 2px 5px 7px 7px white;
    /*background-color: black;*/
    display:inline-block; 
}

这行代码 var el= document.getElementById("a").style.background-image; 怎么能工作?属性中有一个减号... 我本以为应该是 var el= document.getElementById("a").style.backgroundImage; - MDickten
10个回答

82

试一下这个:

document.getElementById('a').style.backgroundImage="url(images/img.jpg)"; // specify the image path here

希望它有所帮助!


5

试试这个!

var el = document.getElementById("a").style.backgroundImage;
if(el == "url(Black-Wallpaper.jpg)") { // full value is provided
   el.style.backgroundImage = "url(/link/to_new_file.png)"; // change it
}

1
这会获取文件名还是路径也会一起获取? - Avisari
@Avisari,它将获取“background-image”CSS属性的值。如果提供文件路径,则其值也将包括文件路径。否则只包含图像! - Afzaal Ahmad Zeeshan
它没有工作:'var el = document.getElementById('a').backgroundImage; if (el == "url(Black-Wallpaper.jpg)") { //el.style.backgroundImage = "url(cross1.png)"; alert("它正在工作"); }' - shajib0o
请使用('a').style.backgrounImage而不是简单的('a').backgroundImage。因为背景是对象样式的属性,而不是对象的属性。 - Afzaal Ahmad Zeeshan
@Avisari,是的,我现在已经更新了我的答案并进行了检查。非常感谢。 - Afzaal Ahmad Zeeshan
显示剩余2条评论

4
你可以用以下方式实现:
第一步:
   var imageUrl= "URL OF THE IMAGE HERE";
   var BackgroundColor="RED"; // what ever color you want

改变BODY的背景颜色
document.body.style.backgroundImage=imageUrl  //changing bg image
document.body.style.backgroundColor=BackgroundColor //changing bg color

更改ID元素

document.getElementById("ElementId").style.backgroundImage=imageUrl
document.getElementById("ElementId").style.backgroundColor=BackgroundColor 

对于具有相同类的元素
   var elements = document.getElementsByClassName("ClassName")
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.background=imageUrl;
        }

2

    

 //Here is an example how to change background image of <div> element using javascript  by feching a new URL form some API.
 // let image teched from API: this is the image you want to put as new background !
// thumbnail image:
// data.picture.thumbnail
//the HTML element whose background needs to be changes is given an id of #thumbnail.

 var thumbUrl = document.querySelector("#thumbnail");
     
//using a function which will update data in the HTML - this is done
//after parsing of the data fetched, I have omitted the steps used for parsing the data.
function updateData(data){
   //data.picture.medium represents our new fetched data containing the URL fo the new image we want to use as background image.
    var newImage=data.picture.medium;
    thumbUrl.style.backgroundImage="url("+newImage+")";
}


2

HTML

<body id="body">
</body>

JavaScript

您可以设置时间。

//Initializing
var i = 0;
var images = []; //array
var time = 3000; // time in millie seconds

//images

images[0] = "url(./Images/1.jpg)";
images[1] = "url(./Images/2.jpg)";
images[2] = "url(./Images/3.jpg)";
//function

function changeImage() {
    var el = document.getElementById('body');
    el.style.backgroundImage = images[i];
    if (i < images.length - 1) {
        i++;
    } else {
        i = 0;
    }
    setTimeout('changeImage()', time);
}

window.onload = changeImage;

CSS

overflow-x: hidden;
margin: 0;
padding: 0;
width: 100%;
height: 100vh;
background-repeat: no-repeat;
background-position: center;

请添加一个解释,说明为什么这个代码可以工作。谢谢! - VFDan

2
//Get the Element from the DOM
var element = document.getElementById("a");

// Change the background image
element.style.backgroundImage = "url('Black-Wallpaper.jpg')"

0

//以下是一个使用JavaScript从API获取新URL并更改元素背景图像的示例。

//让我们从API获取图像:这是您要设置为新背景的图像!

//缩略图:

//数据.picture.thumbnail

//需要更改背景的HTML元素被赋予#thumbnail的ID。

var thumbUrl = document.querySelector("#thumbnail");
 

//使用一个函数来更新HTML中的数据 - 这已经完成了

//在获取数据后进行数据解析,我省略了用于解析数据的步骤。

function updateData(data){

  //data.picture.medium represents our new fetched data containing the URL fo the new image we want to use as background image.
  var newImage=data.picture.medium;
  thumbUrl.style.backgroundImage="url("+newImage+")";

}

2
目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

-1

你可以做到这一点

背景图片:url(${musics[0].image})


-2

兄弟,我也遇到了同样的问题。 后来我意识到当元素的位置是固定或绝对时,JavaScript 无法正常工作。尝试将其位置更改为相对或仅删除位置属性。


这并没有真正回答问题。如果您有不同的问题,可以通过点击提问来提出。如果您想在此问题获得新的答案时得到通知,您可以关注此问题。一旦您拥有足够的声望,您还可以添加悬赏以吸引更多关注。- 来自审核 - jv-k

-3

你可以使用Jquery来实现这个功能

$('#div_id').css("backgroundImage","url(img_path)");
     

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接