1. 程式人生 > 實用技巧 >JS-DOM事件

JS-DOM事件

JS DOM設定元素屬性

設定id為box的這個元素的文字顏色,屬性是減號連線的複合形式時

必需要轉換為駝峰形式

       var box=document.getElementById("box");
       box.style.color='#f00';
       box.style.fontWeight="bold";
       var lis=document.getElementById("list").getElementsByTagName("li");
       // 遍歷每一個li
       for(var i=0,len=lis.length;i<len;i++){
          lis[i].style.color
='#00f'; if(i==0){ lis[i].style.backgroundColor="#ccc"; }else if(i==1){ lis[i].style.backgroundColor="#666"; }else if(i==2){ lis[i].style.backgroundColor="#999"; }else{ lis[i].style.backgroundColor="#333"; } }

innerHTML獲取和設定標籤之間的文字和html內容

className重新設定類,會替換掉原來的類

如果元素有多個class屬性值,那麼會全部獲取到

       var lis=document.getElementById("list").getElementsByTagName("li");
       for(var i=0,len=lis.length;i<len;i++){
           console.log(lis[i].innerHTML);
           lis[i].innerHTML+='程式';
           lis[1].className="current";
       }
       console.log(document.getElementById(
"box").className);

屬性設定與獲取

        var p=document.getElementById("text");
        var user=document.getElementById("user");  // null
        console.log(p.getAttribute("class"));  //p.className
        console.log(user.getAttribute("validate"));
        // 給p設定一個data-color的屬性
        p.setAttribute("data-color","red");
        // 給input設定一個isRead的屬性
        user.setAttribute("isRead","false");
        // 刪除p上的align屬性
        p.removeAttribute("align");

JS事件:

滑鼠事件

onload 頁面載入

onclick 滑鼠點選

onmouseover 滑鼠劃入

onmouseout 滑鼠離開

onmousemove 滑鼠在目標內移動

onfocus 獲得焦點

onblur 失去焦點

onchange 內容改變時


在事件觸發函式中,this是指對該DOM元素的引用

    <input type="button" value="彈 出" onclick="alert('我是按鈕')">
    <!--滑鼠劃過按鈕時呼叫mouseoverFn的函式-->
    <div class="btn" onmouseover="mouseoverFn(this,'#f00')" onmouseout="mouseoutFn(this,'#ff0')">開始</div>
    <div class="btn" onmouseover="mouseoverFn(this,'#0f0')" onmouseout="mouseoutFn(this,'#333')">結束</div>
    <script>
        function mouseoverFn(btn,bgColor){
            // 滑鼠劃過按鈕時,按鈕的背景變為紅色
            btn.style.background=bgColor;
        }
        function mouseoutFn(btn,bgColor){
            btn.style.background=bgColor;
        }

DOM 0級

通過DOM獲取元素

元素.事件=指令碼

執行指令碼可以是一個匿名函式,也可以直接呼叫函式,如果呼叫函式,語法是:ele.事件=函式名,不加括號

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
    <style>
       .lock{width:140px;height:30px;line-height: 30px;background:#00f;
           color:#fff;font-size:14px;text-align:center;border-radius:5px;
           cursor:pointer;margin-top:30px;}
           .unlock{width:140px;height:30px;line-height: 30px;background:#666;
               color:#ccc;font-size:14px;text-align:center;border-radius:5px;
               cursor:pointer;margin-top:30px;}
    </style>
</head>
<body>
    <div class="lock" id="btn">鎖定</div>
    <script>
        // 獲取按鈕
        var btn=document.getElementById("btn");
        function clickBtn(){
           alert("我是按鈕");
        }
        // 點選按鈕呼叫clickBtn這個函式
        btn.onclick=clickBtn;
        // 給按鈕繫結事件,this是對該DOM元素的引用
        btn.onclick=function(){
           // 判斷如果按鈕是鎖定,則顯示為解鎖,變為灰色,否則顯示為鎖定,變為藍色
           if(this.className=="lock"){
               this.className="unlock";
               this.innerHTML="解鎖";
           }else{
               this.className="lock";
               this.innerHTML="鎖定";
           }
        }
    </script>
</body>
</html>

window.onload會在網頁中的所有元素(文字、影象、CSS樣式等)載入完後才觸發執行

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
    // 頁面載入時執行,unload頁面解除安裝
       // 如果不加window.onload,那麼執行指令碼時會找不到div元素
       window.onload=function(){
            // 獲取box
            var box=document.getElementById("box");
            var clicked=function(){
                  alert('我被點選了');
            }
            box.onclick=clicked;
       }
    </script>
</head>
<body>
    <div id="box">這是一個DIV</div>
</body>
</html>

change事件,一般作用域select或checkbox或radio

menu.selectedIndex 獲取select中被選中的元素的下標

<!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>

滑鼠事件:

onsubmit 表單提交

onmousedown 滑鼠按下

onmousemove 滑鼠移動

onmouseup 滑鼠鬆開

onresize 瀏覽器視窗大小調整

onscroll 拖動滾動條

<!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>

鍵盤事件:

onkeydown 按下鍵盤

onkeypress按下鍵盤(只有字母和數字符號)

onkeyup 鬆開鍵盤

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>