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

新手上路,请多包涵

这是我的代码

<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;
}

我想更改’div’的背景图像,哪个类是’ghor’

原文由 shajib0o 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 694
2 个回答

尝试这个:

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

希望能帮助到你!

原文由 immayankmodi 发布,翻译遵循 CC BY-SA 3.0 许可协议

试试这个!

 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
}

原文由 Afzaal Ahmad Zeeshan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题