LoginSignup
22
15

More than 5 years have passed since last update.

SVGに対してclickイベントが反応しない

Last updated at Posted at 2016-10-12

SVGをobjectタグで読み込んで、jqueryでclickイベントを設定したものの、反応しない…

index.html
<div id="hoge">
<object id="moge" type="image/svg+xml" data="hoge.svg">
</div>
index.js
$(function(){

  $("#hoge").on('click', function(){
    console.log("反応しない");
  });

});

解決策

window loadで、svgをjavascriptで取得し、jqueryオブジェクトに変換することで解決した

index.html
<div id="hoge">
<object id="moge" type="image/svg+xml" data="hoge.svg">
</div>
index.js
$(window).on('load', function(){
  var moge = document.getElementById('moge').contentDocument;
  var $moge = $(moge);
  $moge.on('click', function(){
    console.log('反応した');
  });
});

追記

SVGをobjectで読み込み、クリックでページ遷移させようとしたけどできない…
objectを囲う要素をアンカータグにして、hrefを入れても反応しない…
調べた結果:http://subtech.g.hatena.ne.jp/mayuki/20120212/1329046476
CSSで、object要素に

style.css
pointer-events: none;

を設定することで解決した。こっちの方が簡単だった。。
素直にobjectではなくimgでsvgを読み込んだ方がいいのかもしれない

22
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
15