似てて異なるmouseoverイベントとmouseenterイベントの違いを確認しよう。
準備
1.以下のファイルをダウンロードし、好きな場所に解凍する。
jQueryTemplate
1 ファイル 109.82 KB
2.先ほどダウロードしたフォルダはjQueryを用いたWebサイト開発に最適な構成である。これを複製していくことによって新しいプロジェクトを作成する。Templateフォルダを複製しフォルダ名をLesson02_1としよう。
3.以下のようにhtmlを作成する。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>タイトル</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <style> #outer{ width:400px; height:200px; margin:0 auto; padding:100px; background:red; } #inner{ width:400px; height:200px; background:blue; } </style> </head> <body> <!-- ここにコンテンツ --> <div id="outer"> <div id="inner"></div> </div> <script src="js/vendor/jquery-1.12.4.min.js"></script> <script src="js/vendor/jquery-ui-1.12.1.min.js"></script> <script src="js/vendor/jquery.easing.1.3.js"></script> <script src="js/main.js"></script> </body> </html>
4.main.jsを以下のように編集
$(function(){ $('#outer') .on('mouseover',function(e){ console.log('over:'+e.target.id); }) .on('mouseout',function(e){ console.log('out:'+e.target.id); }); });
5.実行してみよう。
内側の青い要素にマウスが移動した時にもイベントが発火しているのがわかる。
6.以下のようにmain.jsを編集する。mouseover->mouseenter,mouseout->mouseleave
$(function(){ $('#outer') .on('mouseenter',function(e){ console.log('over:'+e.target.id); }) .on('mouseleave',function(e){ console.log('out:'+e.target.id); }); });
6.実行してみよう、今度はこ要素(青)にマウスを乗せてもイベントが発火しないことがわかる。状況によって使い分ける必要があるが、通常はmouseenterとmouseleaveの組み合わせで使っておいた方がよいだろう。
コメント