8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

クリックした任意の要素を取得したい。(クリックイベントは発火させない)

Posted at

Webアプリのデバッグモードみたいな感じで、
HTML要素をクリックで選択したい。
でもその時、ページ遷移が発生したりボタンをおした時のイベントが発火してしまうのは困る。

パターン1 全ての要素にイベント付与しておく


//jqueryを使った例
var debugMode = true;

$('*').on('click',function(){
  if(debugMode){
    console.log(this);
    return false;
  }
});

//上でつけたイベントを先頭に持っていく
var handlers = $._data('*').events.click;
handlers.unshift(handlers.pop());

こんな感じで取れそう。

良い点

  • 実装楽

困りそうな点

  • 全要素につけるの無駄っぽい
  • 動的生成した要素に対しても同じ処理をかけないといけない

困りそうな点特に後者が結構辛そう。なので別実装を考えてみる。

パターン2最前面レイヤでイベントだけ拾う

<div id='surface-panel'></div>
# surface-panel {
  z-index: 99999;
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background-color: rgba(0,0,0,0.1);
  }

#surface-panelが最前面にきてクリックイベントを拾うようにしておく。

$('#surface-panel').on('click',function(e){
  $(this).hide()
  console.log document.elementFromPoint(e.clientX,e.clientY)
  $(this).show()
});

あとはdebugModeのon/offに合わせて#surface-panelの表示非表示を切り替えるだけ。

当然各要素に対してのhoverやらのイベントが発火しないのだけれど今回の利用想定としては問題なし。

スクリーンショット 2016-07-19 1.56.07.png

よさそう。

8
8
3

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
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?