Categories: JavaScript

【JavaScript入門】mouseover・mouseoutとmouseenter・mouseleaveの違い

mouseoverとmouseoutの場合

See the Pen
mouseoverとmouseout
by shiakisudev (@shiakisu)
on CodePen.

HTML

<div id="parent">
  <div id="child">
  </div>
</div>
<div id="output"></div>

CSS

#parent{
  width:300px;
  height:300px;
  background-color:pink;
  display:flex;
  justify-content:center;
  align-items: center;
}

#child{
  width:150px;
  height:150px;
  background-color:skyblue;
}

js

let output = document.getElementById("output");
let cnt = 0;
document.getElementById("parent").addEventListener('mouseover',function(e){
  output.innerHTML+=`${++cnt}:入りました。<br>`;
},false);

document.getElementById("parent").addEventListener('mouseout',function(e){
  output.innerHTML+=`${++cnt}:出ました。<br>`;
},false);

mouseenterとmouseleaveの場合

See the Pen
mouseenterとmouseleave
by shiakisudev (@shiakisu)
on CodePen.

HTML

<div id="parent">
  <div id="child">
  </div>
</div>
<div id="output"></div>

CSS

#parent{
  width:300px;
  height:300px;
  background-color:pink;
  display:flex;
  justify-content:center;
  align-items: center;
}

#child{
  width:150px;
  height:150px;
  background-color:skyblue;
}

js

let output = document.getElementById("output");
let cnt = 0;
document.getElementById("parent").addEventListener('mouseenter',function(e){
  output.innerHTML+=`${++cnt}:入りました。<br>`;
},false);

document.getElementById("parent").addEventListener('mouseleave',function(e){
  output.innerHTML+=`${++cnt}:出ました。<br>`;
},false);

以上で記事の解説はお終い!

HTML、CSS、JavaScriptをもっと勉強したい方にはUdemyがオススメ!同僚に差をつけよう!

issiki_wp