事件類型
onblur
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
// 頁面加載
window.onload=init;
// 初始化
function init(){
// 獲取下拉菜單
var menu=document.getElementById("menu");
// 給菜單綁定change事件,一般作用域select或checkbox或radio
menu.onchange=function(){
// 獲取當前選中的值
//var bgcolor=this.value;
var bgcolor=menu.options[menu.selectedIndex].value;
// 如果bgcolor爲空,則下面的腳本將不執行
// if(bgcolor=="")return;
// 設置body的背景色
// 如果bgcolor爲空,則將背景色設爲白色,否則是選擇的顏色
if(bgcolor==""){
document.body.style.background="#fff";
}else{
document.body.style.background=bgcolor;
}
}
}
</script>
</head>
<body>
<div class="box">
請選擇您喜歡的背景色:
<select name="" id="menu">
<option value="">請選擇</option>
<option value="#f00">紅色</option>
<option value="#0f0">綠色</option>
<option value="#00f">藍色</option>
<option value="#ff0">黃色</option>
<option value="#ccc">灰色</option>
</select>
</div>
</body>
</html>
打印臺查看效果
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{height:2000px;}
.box{width:200px;height:200px;background:#f00;overflow:auto;}
</style>
</head>
<body>
<div class="box" id="box">
<p>拖動</p>
<p>拖動</p>
<p>拖動</p>
<p>拖動</p>
<p>拖動</p>
<p>拖動</p>
<p>拖動</p>
<p>拖動</p>
<p>拖動</p>
<p>拖動</p>
</div>
<script>
var box=document.getElementById("box");
// 綁定按下的事件
box.onmousedown=function(){
console.log("我被按下了");
};
// 綁定移動的事件
box.onmousemove=function(){
console.log("我被移動了");
};
// 綁定鬆開的事件
box.onmouseup=function(){
console.log("我被鬆開了");
};
// 綁定點擊的事件
box.onclick=function(){
console.log("我被點擊了");
};
// 瀏覽器窗口尺寸發生改變時
window.onresize=function(){
console.log("我的尺寸被改變了");
};
// 拖動滾動條
window.onscroll=function(){
console.log("我被拖動了");
};
box.onscroll=function(){
console.log("我是DIV的滾動條");
};
</script>
</body>
</html>
鍵盤事件與keyCode屬性
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.text span{font-weight:bold;color:#f00;}
em{font-style:normal;}
b{font-weight:normal;}
</style>
</head>
<body>
<div>
<p class="text">
<b id="showcount">您還可以輸入</b>
<span id="totalbox"><em id="count">30</em>/30</span>
</p>
<div class="input">
<textarea name="" id="text" cols="70" rows="4"></textarea>
</div>
</div>
<script>
// 獲取文本框及其他元素
var text=document.getElementById("text");
var total=30;
var count=document.getElementById("count");
var showcount=document.getElementById("showcount");
var totalbox=document.getElementById("totalbox");
// 綁定鍵盤事件
document.onkeyup=function(){
// 獲取文本框值的長度
var len=text.value.length;
// 計算可輸入的剩餘字符
var allow=total-len;
var overflow=len-total;
// 如果allow小於0
if(allow<0){
showcount.innerHTML="您已超出"+overflow;
totalbox.innerHTML='';
}else{
showcount.innerHTML='您還可以輸入';
totalbox.innerHTML='<em id="count">'+allow+'</em>/30';
}
}
</script>
</body>
</html>