Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

html - Making an svg image object clickable with onclick, avoiding absolute positioning

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...