要素にホバーするとその要素が持つ独自データ属性の値を取り出す処理を作っています。
アイコン要素に各独自データ属性を付け、hoverfuncというクラスを付けて、イベントを呼び出します。
そこで5つの星の内、左から2番めの星をホバーした時だけnullになってしまうのですが、何故だか教えて下さい。
よろしくお願いします。
html
1<!DOCTYPE html> 2<html lang="ja"> 3 <head> 4 <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> 5 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> 6 <title>teratail</title> 7 </head> 8 <style type="text/css"> 9 .fa { 10 font-size: 40px; 11 color: #FACC2E; 12 } 13 .star-content { 14 position: relative; 15 width: 200px; 16 height: 50px; 17 background-color: #fafafa; 18 } 19 .position2-1,.position2-2,.position2-3,.position2-4,.position2-5 { 20 position: absolute; 21 color: #BDBDBD; 22 } 23 .position2-1 { 24 top: 0; 25 left: 0%; 26 } 27 .position2-2 { 28 top: 0; 29 left: 20%; 30 } 31 .position2-3 { 32 top: 0; 33 left: 40%; 34 } 35 .position2-4 { 36 top: 0; 37 left: 60%; 38 } 39 .position2-5 { 40 top: 0; 41 left: 80%; 42 } 43 </style> 44 <body> 45 <div class="star-content"> 46 <i class="fa fa-star-o position2-1 hoverfunc" data-num="1"></i> 47 <i class="fa fa-star-o position2-2 hoverfunc" data-num="2"></i> 48 <i class="fa fa-star-o position2-3 hoverfunc" data-num="3"></i> 49 <i class="fa fa-star-o position2-4 hoverfunc" data-num="4"></i> 50 <i class="fa fa-star-o position2-5 hoverfunc" data-num="5"></i> 51 </div> 52 </body> 53 <script type="text/javascript"> 54 window.addEventListener('load', function(){ 55 56 for(var i=0; i < document.getElementsByClassName('hoverfunc').length; i++){ 57 document.getElementsByClassName('hoverfunc')[i].addEventListener('mouseover', function(evn){ 58 alert(evn.target.getAttribute('data-num')); 59 },false); 60 } 61 }); 62 </script> 63</html>
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2015/11/14 18:03
退会済みユーザー
2015/11/14 19:34 編集