简体   繁体   English

如何使用javascript更改外部样式表中的背景图像?

[英]How to change background image in external stylesheet with javascript?

I want to change the background image from external stylesheet. 我想从外部样式表更改背景图像。

For example in external stylesheet background image was: 例如,在外部样式表背景图像中:

#nav
  {
   background-image:url(../images/nav.png);
  }

Now i want to change it through javascript on run time like: 现在我想在运行时通过javascript更改它,如:

#nav
  {
   background-image:url(../images/newImg.png);
  }

I can successfully change this image by using this javascript code: 我可以使用此javascript代码成功更改此图像:

 eval('theRule.style.backgroundImage="../images/newImg.png"');

But issue is: Result looks like that: 但问题是:结果看起来像这样:

#nav
  {
   background-image:url(http//localhost/project/images/newImg.png);
  }

I dont need http//localhost/project/ etc... 我不需要http // localhost / project / etc ...

I just need ../images/newImg.png 我只需要../images/newImg.png

I tried hard to fix this but i did not found any solution yet. 我努力解决这个问题,但我还没有找到任何解决方案。

So Please guide me that how to resolve this issue? 那么请指导我如何解决这个问题?

Thanks for Reading my Question 感谢您阅读我的问题

Regards 问候

Try. 尝试。

rule.style.setProperty("background-image", "../images/newImg.png", "");
rule.style.cssText = rule.style.cssText.replace("../images/nav.png", "../images/newImg.png"); //Replace all images

But if not helped, then do not find easy ways. 但如果没有帮助,那就找不到简单的方法了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM