複習之JavaScript基本語法(六)——事件監聽總彙
阿新 • • 發佈:2018-12-11
事件監聽
簡單事件監聽 btn.onclick 點選事件
<div class="box" id="box"> <H1> 測試模組</H1> <H1> 測試模組</H1> <H1> 測試模組</H1> <H1> 測試模組</H1> <H1> 測試模組</H1> <H1> 測試模組</H1> </div> <script> var box =document.getElementById("box"); //繫結按下的事件 box.onmousedown =function () { console.log("我被按下了"); } //繫結移動的事件 box.onmousemove=function () { console.log("我被移動了"); } box.onmouseup =function () { console.log("我被鬆開了"); } window.onresize=function () { console.log("我的瀏覽器尺寸被改變了"); } box.onscroll =function () { console.log("我被拖動了"); } </script>
驗證手機號
//驗證手機號 <input type="text" id="phone" placeholder="請輸入手機號碼"> <p id="tip" style="display: none">請輸入有效的手機號碼</p> <script> var phone=document.getElementById("phone"); var tip =document.getElementById("tip") //文字框獲取焦點時 phone.onfocus=function () { //讓tip顯示 tip.style.display='block'; //tip.style.display='none';//隱藏 } } //文字框失去焦點時 phone.onblur=function () { //獲取文字框的值 var phoneVal =this.value; //如果正確 if (phoneVal.length==11 && isNaN(phoneVal) ==false){ tip.innerHTML='ok'; }else { tip.innerHTML='error'; } } </script>
按鈕顏色文字改變
<div class="lock" id="btn">鎖定</div> <script> //獲取按鈕 var btn =document.getElementById("btn"); //給按鈕繫結事件 btn.onclick=function () { // if(this.innerHTML=="鎖定") if(this.className=="lock"){ this.className="unlock"; this.innerHTML="解鎖"; }else { this.className="lock"; this.innerHTML="鎖定"; } } </script>
限制輸入框字數
- onkeyup鍵盤點選事件
var total =30;
var text=document.getElementById("text");
var count =document.getElementById("count");
//在事件觸發的function裡,用一個引數接受事件物件
document.onkeyup =function (ev) {
console.log(ev.keyCode)
var len =text.value.length;
var allow =total-len;
count.innerHTML =allow;
if(allow<=0){
alert("超過30個字了哦");
}
}
根據下拉選項框改變背景色
<script>
window.onload =init;
function init() {
//獲取下拉選單
var menu =document.getElementById("bgselect");
//給選單繫結change事件,一般作用於select或CheckBox或radio
menu.onchange =function () {
//獲取當前選中的值
var bgcolor =this.value;
var bgcolor =menu.options[menu.selectedIndex].value;
if (bgcolor == ""){
document.body.style.background="#fff";
}else {
//設定body的背景色
document.body.style.background=bgcolor;
}
}
}
</script>
</head>
<body>
<div class="box">
請選擇您喜歡的背景色:
<select name="bgselect" id="bgselect">
<option value="">請選擇</option>
<option value="#f00">紅色</option>
<option value="#0f0">藍色</option>
<option value="#ff0">黃色</option>
<option value="#ccc">灰色</option>
</select>
</div>
輸入框焦點獲取和喪失事件
<input id="i1" type="text" value="請輸入賬號"/>
input1.onfocus =function () {
if (this.value=="請輸入賬號"){
this.value=""
}
}
input1.onblur =function () {
alert("你輸入的內容:"+this.value)
}