Last active
August 29, 2015 13:56
-
-
Save YoshinoriKobayashi/9154558 to your computer and use it in GitHub Desktop.
JavaScript Event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- JavaScript のイベントについて | |
********************************* | |
基礎 Ajax + JavaScript | |
P204 | |
--> | |
<input type="button" value="Click me!" onClick"alert('hello')"> | |
<!-- イベントのデフォルト動作を止める --> | |
<!-- イベントの中で、return false を指定すると動きをやめることができる。 --> | |
<a link="index.html" onClick="alert('hello'); return false"> | |
<!-- | |
マウスを乗せたり離したりすると背景が変わる。 | |
thisはイベントが発生した要素を示す。 | |
styleは、cssのスタイルを示すオブジェクト | |
--> | |
<p onmouseover="this.style.backgroundColor='pink'" onmouseout="this.style.backgroudColor='white'"> | |
<!-- | |
ページの読み込みをしてからイベントを実行する。 | |
--> | |
<p id="p1">ここにマウスポインタを合わせてみましょう</p> | |
<script type="text/javascript"> | |
window.onload = init; | |
<!-- 初期化 --> | |
function init(){ | |
var p = document.getElementById("p1"); | |
p.onmouseover = setColor; | |
p.onmouseout = resetColor; | |
} | |
//<中略> | |
</script> | |
<!-- | |
P211 | |
イベントハンドラとクロージャ | |
--> | |
<p id="p1">マススを乗せるとピンクになります。</p> | |
<p id="p2">マススを乗せると黒くなります。</p> | |
<script type="text/javascript"> | |
// ページあ読み込まれたといに実行 | |
window.onload = init; | |
// 初期化 | |
function init() { | |
var p = document.getElementById("p1"); | |
setHandler(p, "pink","red"); | |
p = document.getElementById("p2"); | |
setHandler(p,"black","white"); | |
} | |
// クロージャとは | |
// 内側の関数は、外側の関数のローカル変数と引数を保持する | |
// ローカル変数と組み合わされた関数の中の関数は、クロージャという。 | |
function setHandler(elem,col1,col2) { | |
// ポイントを合わせたときのイベントハンドラ | |
elem.onmouseover = function(){ | |
this.style.backgroundColor = col1; | |
this.style.color = col2; | |
} | |
// ポインタを話したときのイベントハンドラ | |
elem.onmouseout = function() { | |
this.style.backgroundColor = "white"; | |
this.style.color = "black"; | |
} | |
} | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment