简体   繁体   中英

How to change a div background image?

Peace and Blessing be Upon us all.

Basically I have a div say:

<div class="divele" style="background: url("/image/bkimg.jpg") top center no-repeat;background-size:cover;"></div>

Then I have an upload button which the user can select an image from his/her computer and save it in the database. After the XHR response with file being saved. The server respond with the new image link the same as /image/bkimg.jpg which this time the old image has replaced with the new uploaded one. Now I need the div to re-request the new image from the server. and this is what i'm doing:

var parts = result;
$('.divele').css({"background": "url("+parts+") top center no-repeat", "background-size": "cover"});

Don't really know why But this does not load the new image.

Much regards

Thanks to this Answer: How to reload/refresh an element(image) in jQuery

Which Explains because both names are the same the browser uses the cached version, which in order to fix it you can simply add an extra unnecessary parameter which will look like:

d = new Date();
$('.divele').css({"background-image": "url("+result+"?"+d.getTime()+")"}); 

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