javascript 是否可以在 SVG 中监听图像加载事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11390830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to listen image load event in SVG?
提问by Rustam
Is it possible to listen for an <image>
load event in SVG? If yes, how to do this?
是否可以<image>
在 SVG 中侦听加载事件?如果是,如何做到这一点?
采纳答案by Erik Dahlstr?m
Yes it's possible.
是的,这是可能的。
In markup:
在标记中:
<image xlink:href="example.png" width="10" height="10"
onload="alert('loaded')"/>
See jsfiddle.
请参阅jsfiddle。
In script:
在脚本中:
<script>
var img = document.createElementNS("http://www.w3.org/2000/svg", "image");
img.addEventListener('load', function() { alert('loaded'); });
// or alternatively:
// img.onload = function() { alert('loaded'); }
img.width.baseVal.value = 100;
img.height.baseVal.value = 100;
img.href.baseVal = "example.png";
</script>
See jsfiddle.
请参阅jsfiddle。
回答by zayquan
I found that this would not work for SVG object created using D3, but the answer here worked great:
我发现这不适用于使用 D3 创建的 SVG 对象,但这里的答案效果很好:
How can I display a placeholder image in my SVG until the real image is loaded?
For example this worked:
例如,这有效:
var img = innerG.append("image")
.attr('onload', function() {
console.log('loaded');
})
.attr("xlink:href", src)
.attr("width", size)
.attr("height", size);
But this did not work:
但这不起作用:
var img = innerG.append("image")
.attr("xlink:href", src)
.attr("width", size)
.attr("height", size);
img.addEventListener('load', function() { console.log('loaded'); });