简体   繁体   English

如何更改div背景图片?

[英]How to change a div background image?

Peace and Blessing be Upon us all. 和平与祝福临到我们所有人。

Basically I have a div say: 基本上我有一个div说:

<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. XHR响应后,文件被保存。 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. 服务器使用与/image/bkimg.jpg相同的新图像链接进行响应,这次链接将旧图像替换为新的上载图像。 Now I need the div to re-request the new image from the server. 现在,我需要div从服务器重新请求新图像。 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 感谢这个答案: 如何在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()+")"}); 

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

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