document.getElementById.style.backgroundImage不起作用 [英] document.getElementById.style.backgroundImage not working

查看:1664
本文介绍了document.getElementById.style.backgroundImage不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据页面的地址为div分配不同的背景图片,例如,如果我的网址是 http://www.mywebsite.com/mysubdirectory/ 我使用下面的代码:

  if(document .URL.indexOf(mysubdirectory)> = 0){
document.getElementById(wrapper)。style.backgroundImage =url('bg-wrapper.jpg');
}

但它不起作用。我甚至添加了一个伪造的document.write命令,只是为了确保代码的其余部分是确定的,并且确实足以证明我的浏览器中出现了虚假行。有什么我可以忽略吗?编辑:谢谢大家的答案 - 当我在代码中使用body而不是getElementById(wrapper)时,图像出现了,所以我怀疑这是一个与路径有关的问题。我调整了向body标签添加一个onload属性,但它仍然无法使用getElementById。任何想法?

解决方案

您的

  document.getElementById(wrapper)。style.backgroundImage =url('bg-wrapper.jpg'); 

代码是正确的。

它在这个jsfiddle中工作正常: http:// jsfiddle。 net / hUuN5 /



你确定图片是正确的。请记住文件的路径是相对于当前页面的位置。不是css目录


I want to assign different background images to a div depending on the page's address, so for example, if my url is http://www.mywebsite.com/mysubdirectory/ I use the following code:

if(document.URL.indexOf("mysubdirectory") >= 0){ 
   document.getElementById("wrapper").style.backgroundImage = "url('bg-wrapper.jpg')";
}

But it's not working. I even added a bogus document.write command just to make sure the rest of the code was ok and sure enough the bogus line showed up in my browser. Is there something I'm overlooking?

EDIT: Thank you all for your answers - when I use body instead of getElementById("wrapper") in my code, the image shows up, so I doubt it's a path-related issue. I trued adding an onload attribute to the body tag but it's still not working with getElementById. Any ideas?

解决方案

Your

document.getElementById("wrapper").style.backgroundImage = "url('bg-wrapper.jpg')";

code is correct.

It works fine in this jsfiddle: http://jsfiddle.net/hUuN5/

Are you sure the image is correct. Remember that the path to the file is relative to the location of the current page. NOT the css directory

这篇关于document.getElementById.style.backgroundImage不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆