javascript 如何将点击事件绑定到对象标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25916403/
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
How to bind click event to object tag?
提问by Pirune
I have this code
我有这个代码
<object data="images/logo.svg" type="image/svg+xml" class="icon-logo"></object>
and jquery
和jQuery
$(".icon-logo").click(function() {
.....
});
but I can't click event.
但我无法点击事件。
回答by toesslab
1. Issue: Event handling
1. 问题:事件处理
Concerning the jQuery part, try to use event delegation.
关于 jQuery 部分,尝试使用事件委托。
From the docs:
从文档:
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
.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>
Edit after @Kaiido's comment:
在@Kaiido 的评论后编辑:
2. Issue: The <object>
element can't be clicked.
2. 问题:<object>
无法点击元素。
One possibility could be to not use an <object>
at all but an <img>
tag instead as suggested in this SO answer: make an html svg object also a clickable link.
一种可能性可能是根本不使用 an<object>
而是使用一个<img>
标签,而不是按照此 SO 答案中的建议:使 html svg 对象也是一个可点击的链接。
2. Issue: Empty HTML-tag
2. 问题:空的 HTML 标签
This kind of tag <object>
needs some content to show up on the page.
Your tag:
<object data="images/logo.svg" type="image/svg+xml" class="icon-logo"></object>
这种标签<object>
需要一些内容才能显示在页面上。
你的标签:
<object data="images/logo.svg" type="image/svg+xml" class="icon-logo"></object>
is not having any inner HTML-Content, so you won't be able to click it.
没有任何内部 HTML 内容,因此您将无法单击它。
回答by duhaime
The easiest way to accomplish this goal is to wrap the object tag in a div, bind the click listener to the div, and add pointer-events: none
to the object tag's styles.
实现此目标的最简单方法是将对象标签包装在一个 div 中,将点击侦听器绑定到该 div,然后添加pointer-events: none
到对象标签的样式中。
Sample fiddle:
样品小提琴:
.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>