勉強目的でマウスの動きに合わせて要素を移動させようとしています。
しかしうまくいきません。
ソースは以下のように書きました
ファイル名はindex.htmlです。
html
1<!DOCTYPE html> 2<html lang=“ja”> 3 4<head> 5 <meta charset=“UFT-8”> 6 <title>JSの練習です</title> 7 8 <style> 9 body { 10 background: #e02; 11 font-family: Meiryo; 12 } 13 14 div#target_element{ 15 background: #faf; 16 width: 300px; 17 padding: 0px; 18 text-align: center; 19 border: 5px solid #4e4; 20 position: absolute; top:10px; left:0px; 21 } 22</style> 23 24</head> 25 26 <body id="bobobo"> 27 28 <div id="target_element"> 29 <h1>CSS入門</h1> 30 <p>はじめてのCSS</p> 31 </div> 32 33 <script> 34 (function() { 35 'use strict'; 36 37 var target = document.getElementById('target_element'); 38 var mousePositionX ; 39 var mousePositionY ; 40 41 function getMousePosition(e){ 42 try{ 43 mousePositionX = e.clientX 44 mousePositionY = e.clientY 45 console.log("no error!"); 46 console.log(e.clientX); 47 console.log(e.clientY); 48 }catch (error){ 49 console.log(error); 50 console.log("error!"); 51 mousePositionX = 0; 52 mousePositionY = 0; 53 }} 54 55 target.style.left = mousePositionX + 'px'; 56 target.style.top = mousePositionY + 'px'; 57 console.log("aaa3"); 58 59 60 61 62 // ------------------------------------------------------------ 63 // イベントのリッスンを開始する 64 // ------------------------------------------------------------ 65 // イベントリスナーに対応している 66 document.getElementById('bobobo').addEventListener('mousemove',function(){ 67 getMousePosition(); 68 console.log("aaa4") 69 }); 70 71 })(); 72 </script> 73 74 </body> 75</html>
chromeのデベロッパーツールのコンソールにはこのように表示されました。
どうすればよいでしょうか。
御教示お願いします。
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。