简体   繁体   中英

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:

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

I can successfully change this image by using this javascript code:

 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...

I just need ../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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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