mousemove不能处理对象元素

时间:2016-11-09 16:10:48

标签: javascript html object svg

有没有办法让mousemove事件处理程序适用于HTML< object>标签?我有这样的HTML:

<object type="image/svg+xml" data="myfile.svg"></object>
<img src="myfile.svg"/>

和一些像这样的JavaScript / jQuery:

$("img, object").on("mousemove", function() {
  $("body").css("background-color","#f0f");
});
$("img, object").on("mouseleave", function() {
  $("body").css("background-color","transparent");
})

mousemove仅适用于img标记。将pointer-events: all应用于objectobject *似乎没有帮助。

这是fiddle

$("img, object").on("mousemove", function() {
  $("body").css("background-color","#f0f");
});

$("img, object").on("mouseleave", function() {
  $("body").css("background-color","transparent");
})
img, object {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Mouse over the images to change the background color.  It doesn't seem to work for the object tag.

<h2>SVG as &lt;object&gt;</h2>

<object type="image/svg+xml" data="https://upload.wikimedia.org/wikipedia/commons/e/ea/Converted_to_SVG.svg"></object>

<h2>SVG as &lt;img&gt;</h2>

<img src="https://upload.wikimedia.org/wikipedia/commons/e/ea/Converted_to_SVG.svg"/>

2 个答案:

答案 0 :(得分:2)

您是否尝试过使用onmouseenter?或者鼠标移动时你想做些什么?

如果是这样,我建议你将对象包装成一个内联div,并将监听器添加到div中,并在对象上将指针事件设置为none。

请参阅以下示例:

$("img, .objectwrap").on("mousemove", function() {
  $("body").css("background-color","#f0f");
});

$("img, .objectwrap").on("mouseleave", function() {
  $("body").css("background-color","transparent");
})
img, object {
  width: 100px;
}
object {
  pointer-events:none;
  }
.objectwrap {
  display:inline-block;
  background-color:red;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Mouse over the images to change the background color.  It doesn't seem to work for the object tag.

<h2>SVG as &lt;object&gt;</h2>

<div class="objectwrap">
<object type="image/svg+xml" data="https://upload.wikimedia.org/wikipedia/commons/e/ea/Converted_to_SVG.svg"></object>
</div>
<h2>SVG as &lt;img&gt;</h2>

<img src="https://upload.wikimedia.org/wikipedia/commons/e/ea/Converted_to_SVG.svg"/>

答案 1 :(得分:0)

object标记表示不被视为DOM的一部分。这样做是为了使用户可以直接与之交互。它最初是为Flash等外部应用程序设计的。

请参阅:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object