JavaScript Tutorial/Event/Target
Содержание
Event Bubbling Demonstration
<html onclick="alert("Event is now at the HTML element.")">
<head>
<title>Event Bubbles</title>
<script type="text/javascript">
function init() {
window.onclick = winEvent
document.onclick = docEvent;
document.body.onclick = docBodEvent;
}
function winEvent() {
alert("window object level.");
}
function docEvent() {
alert("document object level.");
}
function docBodEvent() {
alert("BODY element.");
}
</script>
</head>
<body onload="init()">
<form onclick="alert("FORM")">
<input type="button" value="Button "main1"" name="main1" onclick="alert("Button: " + this.name)" />
</form>
</body>
</html>
Get key event target element id
<html>
<head>
<title>Key Events Example</title>
<script type="text/javascript">
function handleEvent(oEvent) {
var oTextbox = document.getElementById("txt1");
oTextbox.value += "\n>" + oEvent.type;
oTextbox.value += "\n target is " + (oEvent.target || oEvent.srcElement).id;
}
</script>
</head>
<body>
<P>Type some characters into the first textbox.</p>
<P><textarea id="txtInput" rows="15" cols="50"
onkeypress="handleEvent(event)"></textarea></p>
<P><textarea id="txt1" rows="15" cols="50"></textarea></p>
</body>
</html>
Get mouse event target
<html>
<head>
<title>Mouse Events Example</title>
<script type="text/javascript">
function handleEvent(oEvent) {
var oTextbox = document.getElementById("txt1");
oTextbox.value += "\n target is " + (oEvent.target || oEvent.srcElement).id;
}
</script>
</head>
<body>
<P>Use your mouse to click and double click the red square.</p>
<div style="width: 100px; height: 100px; background-color: red"
onclick="handleEvent(event)"
id="div1"></div>
<P><textarea id="txt1" rows="15" cols="50"></textarea></p>
</body>
</html>
W3C Event Capture and Bubble
<html>
<head>
<title>W3C DOM Event Propagation</title>
<script type="text/javascript">
function init() {
window.onclick = winEvent;
document.onclick = docEvent;
document.body.onclick = docBodEvent;
document.addEventListener("click", docEvent, true);
document.forms[0].addEventListener("click", formCaptureEvent, true);
document.forms[0].addEventListener("click", formBubbleEvent, false);
}
function winEvent(evt) {
alert("window object level (" + getPhase(evt) + ").");
}
function docEvent(evt) {
alert("Document level (" + getPhase(evt) + ").");
}
function docBodEvent(evt) {
alert("BODY level (" + getPhase(evt) + ").");
}
function formCaptureEvent(evt) {
alert("FORM only on CAPTURE.");
}
function formBubbleEvent(evt) {
alert("FORM only on BUBBLE.");
}
function getPhase(evt) {
switch (evt.eventPhase) {
case 1:
return "CAPTURING";
break;
case 2:
return "AT TARGET";
break;
case 3:
return "BUBBLING";
break;
default:
return "";
}
}
</script>
</head>
<body onload="init()">
<form>
<input type="button" value="Button "main1"" name="main1" onclick="alert("button (" + getPhase(event) + ").")" />
</form>
</body>
</html>