如何将点击事件绑定到对象标记

How to bind click event to object tag?

本文关键字:对象 绑定 事件      更新时间:2023-09-26

我有这个代码

<object data="images/logo.svg" type="image/svg+xml" class="icon-logo"></object>

和jquery

$(".icon-logo").click(function() {
.....
});

但我无法点击事件。

实现此目标的最简单方法是将对象标记封装在div中,将click监听器绑定到div,并将pointer-events: none添加到对象标记的样式中。

样品小提琴:

.clickable {
  background: red;
  width: 100px;
  height: 100px;
  border-radius: 100px;
  overflow: hidden;
}
object {
  width: 100%;
  pointer-events: none;
}
<div class='clickable' onclick='alert("WOW")'>
  <object type='image/svg+xml' data='https://douglasduhaime.com/assets/images/icons/home.svg' />
</div>

1。问题:事件处理

关于jQuery部分,请尝试使用事件委派。

来自文档:

.on()方法将事件处理程序附加到当前选定的集合jQuery对象中元素的。

$(document).on('click', '.icon-logo', function(event) {
    document.write('Event type: ' + event.type);
    document.write('<br>CSS-Class: ');
    document.write($(this).attr('class'));
});
// As said in the docs, you can attach multiple events to multiple selectors. 
// A typical example of use may be:
// $(document).on('change blur', '.icon-logo .some-other-class', function() {...}
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<object data="images/logo.svg" type="image/svg+xml" class="icon-logo" style="cursor: pointer;">Click me!</object>


在@Kaiido的评论后编辑:

2.问题:<object>元素无法点击

一种可能性是根本不使用<object>,而是使用<img>标签,如SO回答中所建议的:使html svg对象也成为可点击的链接


2.问题:空HTML标记

这种标签<object>需要一些内容才能显示在页面上。

您的标签:

<object data="images/logo.svg" type="image/svg+xml" class="icon-logo"></object>

没有任何内部HTML内容,因此您将无法单击它。