javascript, 如果加载相同的图像,图像 onload() 在 webkit 中不会触发
我有一个 元素,我正在更改其
src
属性。该元素附加了一个 onload
处理函数。每次我更改 src 属性并且图像加载时,处理程序函数都应该运行。
在 Chrome 和 Safari 中,如果我分配与之前相同的 src,则处理程序函数不会运行。在分配与之前相同的 src 之前,我尝试了 imgElement.src=''
、imgElement.src= null
、imgElement.src='notExistingFile.jpg'
但这些都不起作用。
请帮忙。以前有人遇到过这个问题吗?
编辑:它的工作原理是在分配与之前相同的 src 之前执行 imgElement.src = '' :
imgElement.src = '';
imgElement.src = 'image.jpg';
I have an <img>
element and I'm changing its src
attribute. The element has an onload
handler function attached. Each time i change the src attribute and the image loads the handler function should run.
In Chrome and Safari, if I assign the same src as the one before, the handler function is not run. Before assigning that same src as before i've tried imgElement.src=''
, imgElement.src= null
, imgElement.src='notExistingFile.jpg'
and none of it works.
Please help. Anyone had this problem before?
Edit: it worked by doing imgElement.src = '' before assigning the same src as before:
imgElement.src = '';
imgElement.src = 'image.jpg';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是已知错误。这是该链接的解决方法:
This is a known bug. Here's the workaround from that link:
我认为你的问题在于你在更改 src 值之后分配 onload 事件,因此一旦图像已经加载到缓存中,浏览器就会在分配事件之前加载它。意味着不要这样做:
这样做:
I think your problem here is just that you are assigning the onload event after you change the src value, so once the image has already been loaded to the cache, the browser load's it before the assignment of the event. Means that instead of doing this:
do this:
要添加到 Matt Ball 的答案中,请考虑使用 img.onload 而不是 img.addEventListener()。
img.onload 更易于阅读并且跨用户代理工作得更好。
To add to Matt Ball's answer, consider img.onload instead of img.addEventListener().
img.onload is easier to read and works better across user agents.