使用 onclick 使 svg 图像对象可点击,避免绝对定位 [英] Making an svg image object clickable with onclick, avoiding absolute positioning
问题描述
我尝试将我网站上的图像从 img
更改为 svg
,将 img
标签更改为 embed
> 和 object
标签.但是,实现以前包含在 img
标签中的 onclick
函数被证明是最困难的.
我发现将 onclick
放在 object
或 embed
标签内时没有效果.
所以,我专门为 svg 制作了一个 div
,并将 onclick
放在这个 div
标签中.但是,除非访问者点击图像的边缘/填充,否则没有效果.
我已经阅读了关于覆盖 div
的内容,但我试图避免使用 absolute
定位,或者根本不指定 position
.
还有其他方法可以将 onclick 应用到 svg 吗?
有人遇到过这个问题吗?欢迎提出问题和建议.
您可以在 svg 本身中设置一个 onclick 事件,我在工作中一直这样做.在你的 svg 的空间上做一个矩形,(所以最后定义它,记住 svg 使用画家模型)
rect.btn {中风:#fff;填充:#fff;填充不透明度:0;中风不透明度:0;}
然后作为 rect 的属性添加 onclick(这也可以使用 js 或 jquery 完成).
<svg xmlns="http://www.w3.org/2000/svg";版本=1.1"><g><circle ...//你的 img svg<rect class="btn";x=0"y=0"宽度=10"高度=10"onclick="alert('click!')";/></g></svg>
这几乎适用于所有浏览器:http://caniuse.com/svg
I have tried to change the images on my site from img
to svg
, changing img
tags to embed
and object
tags. But, implementing the onclick
function, which previously was contained in the img
tag, is proving most difficult.
I found onclick
had no effect when placed inside the object
or embed
tag.
So, I made a div
exclusively for the svg, and placed onclick
in this div
tag. But, no effect unless visitor clicks on the edges/padding of the image.
I have read about overlaying a div
, but am trying to avoid using absolute
positioning, or specifying position
at all.
Is there another way to apply onclick to a svg?
Has anyone encountered this problem? Questions and suggestions are welcome.
You can have an onclick event in the svg itself, I do this all the time in my work. make a rect over the space of your svg, (so define it last, remember svg uses the painters model)
rect.btn {
stroke:#fff;
fill:#fff;
fill-opacity:0;
stroke-opacity:0;
}
then as an attribute to the rect add the onclick (this can be done with js or jquery as well).
<div>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g>
<circle ... //your img svg
<rect class="btn" x="0" y="0" width="10" height="10" onclick="alert('click!')" />
</g>
</svg>
</div>
this will work in almost all browsers: http://caniuse.com/svg
这篇关于使用 onclick 使 svg 图像对象可点击,避免绝对定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!