示例:复制用户输入、使用单一按键切换不同功能(开始/暂停录音)
示例效果:
JS代码如下(注:页面功能看似简单,JS代码却并不简单):
var noteInput, noteName, textEntered, target; // Declare variables
noteName = document.getElementById('noteName'); // Element that holds note
noteInput = document.getElementById('noteInput');// Input for writing the note
function writeLabel(e) { // Declare function
if (!e) { // If event object not present
e = window.event; // Use IE5-8 fallback
}
target = e.target || e.srcElement; // Get target of event
textEntered = target.value; // Value of that element
noteName.textContent = textEntered; // Update note text
}
function recorderControls(e) { // Declare recorderControls()
if (!e) { // If event object not present
e = window.event; // Use IE5-8 fallback
}
target = e.target || e.srcElement; // Get the target element
if (e.preventDefault) { // If preventDefault() supported
e.preventDefault(); // Stop default action
} else { // Otherwise
e.returnValue = false; // IE fallback: stop default action
}
switch(target.getAttribute('data-state')) { // Get the data-state attribute
case 'record': // If its value is record
record(target); // Call the record() function
break; // Exit function to where called
case 'stop': // If its value is stop
stop(target); // Call the stop() function
break; // Exit function to where called
// More buttons could go here...
}
}
function record(target) { // Declare function
target.setAttribute('data-state', 'stop'); // Set data-state attr to stop
target.textContent = 'stop'; // Set text to 'stop'
}
function stop(target) {
target.setAttribute('data-state', 'record'); //Set data-state attr to record
target.textContent = 'record'; // Set text to 'record'
}
if (document.addEventListener) { // If event listener supported
document.addEventListener('click', function(e) {// For any click document
recorderControls(e); // Call recorderControls()
}, false); // Capture during bubble phase
// If input event fires on noteInput input call writeLabel()
noteInput.addEventListener('input', writeLabel, false);
} else { // Otherwise
document.attachEvent('onclick', function(e) { // IE fallback: any click
recorderControls(e); // Calls recorderControls()
});
// If keyup event fires on noteInput call writeLabel()
noteInput.attachEvent('onkeyup', writeLabel);
}
HTML代码如下:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript & jQuery - Chapter 6: Events - Example</title>
<link rel="stylesheet" href="css/c06.css" />
</head>
<body>
<div id="page">
<h1>List King</h1>
<h2 id="noteName">Audio Note</h2>
<form action="http://example.org/">
<label for="noteInput">Enter note name:</label>
<input type="text" id="noteInput" />
<div id="buttons">
<a data-state="record" href="">record</a>
</div>
</form>
</div>
<script src="js/example.js"></script>
</body>
</html>
CSS代码:(参考源码-JavaScript&jQuery交互式前端开发-第6章-事件-Focus和blur事件,http://blog.csdn.net/hpdlzu80100/article/details/52651002)