Force recalculation of $(...).css("background-image") on linked stylesheet reload
(I only need functionality in Chrome)
Context:
I'm hacking together a node.js script that automatically watches the files it serves for changes and then uses a websocket connection to push a message to a control page in the browser that manages the reload of assets. For instance, if an html page has an<img href="foo.jpg" />
, the server will watch the jpg and send a message to the page that "foo.jpg" has changed. At this point I use javascript to reload reload the image (src = src+"?cachbust=00002", or some-such).
Problem:
When a background image changes I loop through the page elements to find any references to the image and reset it with new query string to reload it. To do this I use jquery's$(...).css("background-image", ...)
solution. That works, but when I subsequently change the the value for the url in the css (ie, background: url(foo.jpg); => background: url(bar.jpg)), the background-img value doesn't change.
For css changes, my script reloads the l开发者_如何转开发inked stylesheet. My suspicion is that the value I assigned via javascript is taking precedence over the value the css rule in the linked stylesheet ala an inline style attribute.
Question:
Is there anyway to force Chrome to recalculate and apply the value from the external stylesheet and apply to elements that have had styles assigned by jquery's$(...).css("...","...")
functionality?
Thanks everybody.
Generally, if you want to change/reload a background image on some event, try embedding a span or other element inside the main element, and set a background image on that. Then you can replace that element without having to reload an entire stylesheet. Something like this:
<div class="content-element">
<span class="bg-image-element" style="background-image: url('old.png')"></span>
<!-- .... other stuff .... -->
</div>
<script>
$('.some-element').someEvent(function() {
$('.bg-image-element').replaceWith(<span class="bg-image-element" style="background-image: url('new.png')"></span>
});
</script>
I have not seen consistent behavior when changing just the css background-image via javascript/jQuery works. But replacing an entire element does seem to force a background image reload.
For css changes, my script reloads the linked stylesheet. My suspicion is that the value I assigned via javascript is taking precedence over the value the css rule in the linked stylesheet ala an inline style attribute.
That's exactly right. Setting CSS via jQuery like that has the same effect as putting a "style" attribute on an element (which in fact it does do). That overrides something picked up via selector in the CSS.
You should be able to un-set the local style on the elements with
$(...).css("background-image", "");
精彩评论