【发布时间】:2012-07-08 14:27:21
【问题描述】:
是否可以在 SVG 中监听 <image> 加载事件?如果是,该怎么做?
【问题讨论】:
-
“真实”和“可能”的意思一样吗?
-
你所说的
是指 ?
-
SVG
标签,不是任何 html 标签
标签: javascript image svg load
是否可以在 SVG 中监听 <image> 加载事件?如果是,该怎么做?
【问题讨论】:
标签: javascript image svg load
是的,这是可能的。
在标记中:
<image xlink:href="example.png" width="10" height="10"
onload="alert('loaded')"/>
见jsfiddle。
在脚本中:
<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>
见jsfiddle。
【讨论】:
load 事件 <image>。我建议像 img = new Image(); img.onload = …; img.src = 'example.png' 这样加载图像,而不是像 Erik 的示例中那样使用 svg image 标签。
我发现这不适用于使用 D3 创建的 SVG 对象,但这里的答案很有效:
How can I display a placeholder image in my SVG until the real image is loaded?
例如这有效:
var img = innerG.append("image")
.attr('onload', function() {
console.log('loaded');
})
.attr("xlink:href", src)
.attr("width", size)
.attr("height", size);
但这不起作用:
var img = innerG.append("image")
.attr("xlink:href", src)
.attr("width", size)
.attr("height", size);
img.addEventListener('load', function() { console.log('loaded'); });
【讨论】:
onload。但事件名称不同:SVGLoad 不是 load。见w3.org/TR/SVG/interact.html#LoadEvent
.attr("xlink:href", src) 第二个放在img.addEventListener('load', function() { console.log('loaded'); }); 之后,否则它将不起作用 - 请注意在对您有用的示例中,首先设置 onload attr,然后再设置 src。