简体   繁体   中英

Get relative CSS URL path in Javascript

NOTE: I finally found an exact duplicate question and good answer at: Get script path

I have a background-image defined with a path relative to my css file.

.my-image-class {
  background-image: url("../images/my_bg_image.png");
}

I would like change this path in JavaScript so that it now points to ../images/my_updated_bg_image.png . However simply changing the style declaration in JavaScript unfortunately changes the meaning of the relative path from the CSS location to the HTML location.

Is there a way to extract an absolute URL from a relative CSS URL?

If not is there a way to extract an absolute URL of the source of a currently running JavaScript function? This would give me the same information because my JS files are also relative to the images files.

Other solutions?

This is a similar question to javascript - How to use a image file relative to a url path? but the class swapping trick suggested there won't work for me because I actually have a variable list of these background images.

EDIT: Background info. The web app (Django based) is serving HTML content entirely separately from static js, image, and css files. The static content is in a

static/
  js/
  css/
  images/

file structure. So I know the relative relationships among these files. However the absolute URL's to the HTML content and the static content will likely be changing. So I don't want mix in hard coded URL's for HTML content into my js files if I can possibly avoid it. I'm getting the Django template from a 3rd party, so I'd also like to avoid editing that as well.

URLs in CSS stylesheets are relative to the CSS file in which they appear (even if @import ed). If they appear in HTML, they are relative to the base URL of the HTML file which is typically the URL of the HTML file, unless there is a <base href=...> element in the HTML.

So you need to figure out the absolute URL against which the relative URL is resolved and then calculate a relative URL for your image.

You might try seeing if the old image is being served from multiple different places. Lots of web servers accumulate cruft and perhaps you're just putting the new image in a logical, but still wrong, place.

EDIT:

There are a variety of options in between absolute and path relative ../foo style URLs.

Absolute paths: /images/myImage.png .

Protocol relative URLs: //my-domain.com/image/myImage.png

Either of these might let you strike a better balance between specifying as much as you need but no more.

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