javascript - 无法将 mousedown 事件附加到嵌入元素

标签 javascript html svg

我似乎遇到了这种废话,无法理解它。我有一个包含相对复杂的 SVG 的页面(其中嵌入了 6 个其他较小的 SVG),其中嵌入了 embed 标签。当我尝试将 mousedown 事件附加到它时,它根本不起作用。这是标记:

<body>
<embed type="image/svg+xml" src="images/cog.svg" id="cog">
</embed>
</body>

然后在 javascript 中做

$(function(){  
  var cog = document.getElementById("cog");
  document.addEventListener('mousedown', function(e){
    console.log(e);
  });
});

这是行不通的。此外,当我将事件附加到 document 时,当我单击该嵌入对象时它们也不会触发! 我搜索了这个东西 3 个小时,无论我在哪里看,嵌入似乎都应该支持 mousedown,即使没有任何问题。这里有什么问题? 编辑: 如果这里有任何帮助,请查看完整标记的外观(我使用 Foundation 框架): enter image description here

最佳答案

如果CORS不是问题,您可以尝试:

document.querySelector('embed').addEventListener('load', function(){
    this.getSVGDocument().addEventListener('mousedown', function(){
        alert('hello')});
        });

根据 the specs :

3 . If the previous step determined that the content's type is image/svg+xml, then run the following substeps:

  1. If the embed element is not associated with a nested browsing context, associate the element with a newly created nested browsing context,[...]

  2. Navigate the nested browsing context to the fetched resource, with replacement enabled, and with the embed element's node document's browsing context as the source browsing context. (The src attribute of the embed element doesn't get updated if the browsing context gets further navigated to other locations.)

  3. The embed element now represents its associated nested browsing context.

但我找不到任何关于它应该如何处理事件的信息。

然而,当它的 src 被设置并返回一些东西时,事件似乎被新的上下文捕获(无论是到达还是创建)。

参见 @Marius comment对于未设置 src 的演示,它会触发事件。

关于javascript - 无法将 mousedown 事件附加到嵌入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448391/

相关文章:

javascript - 使用鼠标滚轮水平滚动 div-javascript

javascript - XMLHttpRequests 上是否有可用的 NavigationTiming 接口(interface)?

javascript - 针对数据值(value)问题

php - 使用 PHP 遍历 SVG 元素

javascript - onMouseOver 在react.js 应用程序中不起作用

javascript - 如何使用 Material 工具提示为 ag-grid 制作自定义工具提示组件

javascript - 使用 DD-MM-YYYY 格式将某一日期与今天进行比较

javascript - createElement() 与 innerHTML 何时使用?

CSS3 3D 翻转卡片效果与 SVG 元素

html - 将变量从 CSS 或 HTML 传递到内联 SVG