DOM
文檔對象模型(Document Object Model,DOM)是一種用於HTML和XML文檔的編程接口。它給文檔提供了一種結構化的表示方法,可以改變文檔的內容和呈現方式。我們最爲關心的是,DOM把網頁和腳本以及其他的編程語言聯繫了起來。DOM屬於瀏覽器,而不是JavaScript語言規範裏的規定的核心內容。
一、查找元素(選擇器)
1、直接查找
document.getElementById 根據ID獲取一個標籤 document.getElementsByName 根據name屬性獲取標籤集合 document.getElementsByClassName 根據class屬性獲取標籤集合 document.getElementsByTagName 根據標籤名獲取標籤集合
<script> a = document.getElementById('id1'); a = document.getElementsByTagName("div"); //會生成數組 a = document.getElementsByName('name'); //會生成數組 a = document.getElementsByClassName("d1"); //會生成數組 b = a[0].innerText; console.log(b); </script>
2、間接查找
//可以將文本都找出來 parentNode // 父節點 childNodes // 所有子節點 firstChild // 第一個子節點 lastChild // 最後一個子節點 nextSibling // 下一個兄弟節點 previousSibling // 上一個兄弟節點 //不可以將文本找出來 parentElement // 父節點標籤元素 children // 所有子標籤 firstElementChild // 第一個子標籤元素 lastElementChild // 最後一個子標籤元素 nextElementtSibling // 下一個兄弟標籤元素 previousElementSibling // 上一個兄弟標籤元素
例子:
var a = document.getElementById('id1'); //可以將文本都找出來 var b = a.parentNode; charen_list1 = b.childNodes; charen_list1.nextSibling; //不可以將文本找出來 var c = a.parentElement; charen_list2 = c.children; console.log(charen_list2[0])
二、操作
1、內容
innerText 文本 outerText innerHTML HTML內容 outerHTML 重要:value 值 注:以下操作可查詢也可賦值 checkbox -- value -- checked radio //單選,定義一個相同的name可單選 -- value -- checked select -- value --selectedIndex 獲取列表中的索引
簡單例子:
//DOM內容操作 //(1)innerText/innerHTML操作 var text_html = document.getElementById('id1'); var text = text_html.innerText; var html = text_html.innerHTML; alert(text); alert(html); //(2)value操作 var tex = document.getElementById('tex'); console.log(tex.value); //獲得value值 tex.value = 'value' //設置value值 var sel = document.getElementById('sel'); console.log(sel.value) ;
radio、select的value值操作:
<!DOCTYPE html> <html > <head> <title>radio、select的value值操作</title> <meta charset="utf-8"> </head> <body> <ul id="Sex"> <li><input type="radio" name="sex" value="1">男</li> <li><input type="radio" name="sex" value="2">女</li> </ul> <select name="pariviage" id="par"> <option value="1">廣東</option> <option value="2" selected="selected">廣西</option> <option value="3">福建</option> <option value="4">湖南</option> </select> <script> //radio 的value屬性操作 var SEX = document.getElementsByName('sex'); console.log(SEX[0].value) console.log(SEX[1].checked=true) //select的value屬性操作 var Pra = document.getElementById('par'); console.log(Pra.value=4) //可獲取值也可賦值 console.log(Pra.selectedIndex) //獲取列表中的索引 </script> </body> </html>
2、操作樣式:class級別
className // 獲取所有類名,得到的是字符串
classList //獲取所有類名的列表
classList.remove(cls) // 刪除指定類
classList.add(cls) // 添加類
例子:簡陋模態對話框
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> *{ margin: 0; padding: 0; } .hide{ visibility: hidden; /* display: none; 這樣也是可以的*/ } .butt{ position: fixed; left: 200px; top:200px; z-index: 1; } .shadow{ position: fixed; left: 0; right: 0; top: 0; bottom: 0; background: rgba(0,0,0,0.3); z-index: 2; } .mode{ position: fixed; /*fixed:固定 absolute:繼承*/ height: 300px; width: 500px; left: 50%; top: 50%; background: white; margin-left: -250px; /* 以左上角爲起點,向左移動250px,向上移動150px,移動以實際的寬和高的一半 */ margin-top: -220px; z-index: 3; } </style> </head> <body> <div class="butt"> <input type="button" value="模態對話框" id="but" onclick="Show()"> </div> <!-- 模態對話框 --> <div class="shadow hide" id="shadow"></div> <div class="mode hide" id="mode"> <div class="login"> <div>登錄:<input type="text"></div> <div>密碼:<input type="password"></div> <div> <input type="button" value="確定"> <input type="button" value="取消" id="hide" onclick="Hide()"> </div> </div> </div> <script> function Show(){ document.getElementById('shadow').classList.remove('hide'); document.getElementById('mode').classList.remove('hide'); }; function Hide(){ document.getElementById('shadow').classList.add('hide'); document.getElementById('mode').classList.add('hide'); } </script> </body> </html>
特殊:this
<!DOCTYPE html> <html > <head> <title>this特殊屬性</title> <meta charset="utf-8"> <script> function show(arg){ console.log(arg); //獲取到div的標籤 } </script> </head> <body> <div style="height: 50px;width: 50px;cursor: pointer;background: red;text-align: center;line-height: 50px" onclick="show(this);"> 點我 </div> </body> </html>
例子:摺疊菜單,簡單的兩種形式
方法一:用this屬性
<!DOCTYPE html> <html > <head> <title>豎向的摺疊菜單</title> <meta charset="utf-8"> <script> function showmenu(arg) { var Menu = arg; console.log(Menu); var List = Menu.parentElement.children[1]; if (List.style.display=="none") { List.style.display="block"; Menu.className = "title1"; }else { List.style.display="none"; Menu.className = "title"; } } </script> <style type="text/css"> *{margin:0;padding:0;list-style:none;font-size:14px} #nav{margin:10px;text-align:center;line-height:25px;width:200px;} .title{background:#336699;color:#fff;border-bottom:1px solid #fff;cursor:pointer;} .title1{background:#888;color:#000;border-bottom:1px solid #666;cursor:pointer;} .content li{color:#336699;background:#ddd;border-bottom:1px solid #fff;} </style> </head> <body> <div id="nav"> <div> <div class="title" id="menu1" onclick="showmenu(this) ">菜單一</div> <div id="list1" class="content" style="display:none"> <ul> <li><a href="http://www.baidu.com">jQuery</a></li> <li><a href="http://www.baidu.com">Extjs</a></li> <li><a href="http://www.baidu.com">Mootools</a></li> </ul> </div> </div> <div> <div class="title" id="menu2" onclick="showmenu(this)">菜單二</div> <div id="list2" class="content" style="display:none"> <ul> <li>菜單導航</li> <li>層和佈局</li> <li>圖片切換</li> </ul> </div> </div> </div> </body> </html>
方法二:不用this屬性
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>豎向的摺疊菜單</title> <script language = JavaScript> function showmenu(id) { var list = document.getElementById("list"+id); var menu = document.getElementById("menu"+id) if (list.style.display=="none") { document.getElementById("list"+id).style.display="block"; menu.className = "title1"; }else { document.getElementById("list"+id).style.display="none"; menu.className = "title"; } } </script> <style type="text/css"> *{margin:0;padding:0;list-style:none;font-size:14px} #nav{margin:10px;text-align:center;line-height:25px;width:200px;} .title{background:#336699;color:#fff;border-bottom:1px solid #fff;cursor:pointer;} .title1{background:#888;color:#000;border-bottom:1px solid #666;cursor:pointer;} .content li{color:#336699;background:#ddd;border-bottom:1px solid #fff;} </style> </head> <body> <div id="nav"> <div class="title" id="menu1" onclick="showmenu('1') ">菜單一</div> <div id="list1" class="content" style="display:none"> <ul> <li><a href="http://www.baidu.com">jQuery</a></li> <li>Extjs</li> <li>Mootools</li> </ul> </div> <div class="title" id="menu2" onclick="showmenu('2')">菜單二</div> <div id="list2" class="content" style="display:none"> <ul> <li>菜單導航</li> <li>層和佈局</li> <li>圖片切換</li> </ul> </div> </div> </body> </html>
例子:搜索框的兩種實現方法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>搜索框的兩種實現方法</title> <style> .Gar{color: gray} .Bla{color: black} </style> </head> <body> <!-- 搜索框有兩種方法:第一種最常用,但是低級瀏覽器不支持--> <div>方法一:</div> <input type="text" placeholder="請輸入內容"> <div>方法二:</div> <!-- onfocus:單光標點進在裏面時 onblur:單光標沒點在裏面時 --> <input type="text" value="請輸入內容" class="Gar" onfocus="Point(this)" onblur="Out(this)"/> <script > function Point(arg){ if (arg.value == '請輸入內容'){ arg.value = ''; arg.className = "Bla"; } } function Out(arg){ if(arg.value.trim() == "請輸入內容" || arg.value.trim().length == 0){ arg.value = "請輸入內容"; arg.className = 'Gar'; } } </script> </body> </html>
注意:
onfocus:單光標點進在裏面時
onblur:單光標沒點在裏面時
例子:全選,取消,反選
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>多選框</title> </head> <body> <div> <input type="button" value="全選" onclick="Check_All()"> <input type="button" value="取消" onclick="Cancel_All()"> <input type="button" value="反選" onclick="Invert_All()"> </div> <table> <thead> <tr> <th></th> <th>ID</th> <th>NAME</th> <th>PASSWORD</th> </tr> </thead> <tbody id="Checks"> <tr> <td><input class="che1" type="checkbox" value="1" ></td> <td>1</td> <td>翁孟鎧</td> <td>passwd</td> </tr> <tr> <td><input class="che1" type="checkbox" value="2" ></td> <td>2</td> <td>wmk</td> <td>admin</td> </tr> <tr> <td><input class="che1" type="checkbox" value="3" ></td> <td>3</td> <td>張三</td> <td>admin</td> </tr> <tr> <td><input class="che1" type="checkbox" value="4" ></td> <td>2</td> <td>李四</td> <td>admin</td> </tr> <tr> <td><input id="status" class="che1" type="checkbox" value="5" onclick="Check_All_1()" ></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> <script> function Check_All(){ var Check_Box = document.getElementById("Checks").getElementsByClassName('che1'); for(var item in Check_Box){ Check_Box[item].checked = true; } } function Check_All_1(){ var Check_Box = document.getElementById("Checks").getElementsByClassName('che1'); var Check_Status = document.getElementById('status').checked; for(var item in Check_Box){ if(Check_Box[item].checked){ Check_Box[item].checked = false; }else{ Check_Box[item].checked = true; } } } function Cancel_All(){ var Check_Box = document.getElementById("Checks").getElementsByClassName('che1'); for(var item in Check_Box){ Check_Box[item].checked = false; } } function Invert_All(){ var Check_Box = document.getElementById("Checks").getElementsByClassName('che1'); for(var item in Check_Box){ if(Check_Box[item].checked){ Check_Box[item].checked = false; }else{ Check_Box[item].checked = true; } } } </script> </body> </html>
3、屬性:可自定義屬性
attributes // 獲取所有標籤屬性 setAttribute(key,value) // 設置標籤屬性 getAttribute(key) // 獲取指定標籤屬性 /* var atr = document.createAttribute("class"); atr.nodeValue="democlass"; document.getElementById('n1').setAttributeNode(atr); */ action
tab菜單:
<!DOCTYPE html> <html > <head> <title>tab菜單</title> <meta charset="utf-8"> <style> *{margin: 0;padding: 0} .Tab{width: 700px;height: 500px;margin: 0 auto} .Tab .nav{width: 700px;height:53px;border: 0} ul li{list-style-type: none;float: left;margin:0;padding: 15px 20px 15px 20px;font-size: 20px;border: 0;cursor: pointer} .Tab .con{width: 700px;height: 440px;border: 1px solid black} .change{background: red;color: white} .hide{display: none} </style> </head> <body> <div class="Tab"> <div class="nav" id="tab_nav"> <ul> <li onclick="show(this)" Nav="h1">首頁</li> <li onclick="show(this)" Nav="h2">菜單</li> <li onclick="show(this)" Nav="h3">其他</li> </ul> </div> <div class="con" id="tab_con"> <div Con="h1" >首頁內容</div> <div Con="h2" class="hide">菜單內容</div> <div Con="h3" class="hide">其他內容</div> </div> </div> <script> var CON = document.getElementById('tab_con').children; console.log(CON) function show(arg){ var Li_list = arg.parentElement.children; for(var item in Li_list){ var Li = Li_list[item]; Li.className=''; } arg.className = 'change'; var NAV = arg.getAttribute('Nav'); var CON = document.getElementById('tab_con').children; for( var i=0;i<CON.length;i++){ console.log(CON[i]) var C = CON[i].getAttribute('Con'); if(C == NAV){ CON[i].className=""; }else { CON[i].className="hide"; } } } </script> </body> </html>
5、樣式操作:style級別
style.cssText 可對style中的代碼進行讀寫 style.item() 返回給定位置的CSS屬性的名稱 style.length style代碼塊中參數個數 style.getPropertyValue() 返回給定屬性的字符串值 style.getPropertyPriority() 檢測給定屬性是否設置了!important,設置了返回"important";否則返回空字符串 style.removeProperty() 刪除指定屬性 style.setProperty() 設置屬性,可三個參數:設置屬性名,設置屬性值,是否設置爲"important"(可不寫或寫"")
簡單例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="t" style="background-color: yellow; width: 100px; height: 100px">8</div> <script> var tT = document.getElementById("t"); console.log(tT.style.cssText); //width: 100px; height: 100px; background-color: yellow; tT.style.cssText = "background-color: yellow; width: 200px; height: 200px"; //修改屬性 console.log(tT.style.cssText); //width: 200px; height: 200px; background-color: yellow; console.log(tT.style.item("0")); //background-color console.log(tT.style.length); //3 console.log(tT.style.getPropertyValue("background-color")); //yellow console.log(tT.style.getPropertyPriority("background-color")); //空字符串 console.log(tT.style.removeProperty("width")); //200px tT.style.setProperty("width","200px",""); //設置屬性,第三個值爲important優先值,可不寫 </script> </body> </html>
例子:操作標籤style
var obj = document.getElementById('i1') obj.style.fontSize = "32px"; obj.style.backgroundColor = "red";
<input onfocus="Focus(this);" onblur="Blur(this);" id="search" value="請輸入關鍵字" style="color: gray;" /> <script> function Focus(ths){ ths.style.color = "black"; if(ths.value == '請輸入關鍵字' || ths.value.trim() == ""){ ths.value = ""; } } function Blur(ths){ if(ths.value.trim() == ""){ ths.value = '請輸入關鍵字'; ths.style.color = 'gray'; }else{ ths.style.color = "black"; } } </script>
6、標籤操作
a.創建標籤
// 方式一 var tag = document.createElement('a') tag.innerText = "wupeiqi" tag.className = "c1" tag.href = "http://www.cnblogs.com/wupeiqi" // 方式二 var tag = "<a class='c1' href='http://www.cnblogs.com/wupeiqi'>wupeiqi</a>"
b.操作標籤
// 方式一 var obj = "<input type='text' />"; xxx.insertAdjacentHTML("beforeEnd",obj); xxx.insertAdjacentElement('afterBegin',document.createElement('p')) 注意:第一個參數只能是'beforeBegin'、 'afterBegin'、 'beforeEnd'、 'afterEnd' beforeEnd:內部的最後一個 beforeBegin:外部的上邊 afterBegin:內部第一個 afterEnd:外部的下面 // 方式二:創建節點 var tag = document.createElement('a') xxx.appendChild(tag) //從XXX節點的最後一行 xxx.insertBefore(tag,xxx_list[1]) //添加指定位置的前面 xxx.insertAfter(tag,xxx_list[1]) //添加指定位置的後面,注意這是JQ的 xxx.removeChild(xxx_list[3]); //指定位置刪除節點
例子:添加和刪除一行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>添加一行</title> </head> <body> <div> <input type="button" value="添加" onclick="Add()"> <input type="button" value="刪除" onclick="Clean()" </div> <table> <thead> <tr> <th>ID</th> <th>姓名</th> <th>性別</th> <th>用戶名</th> </tr> </thead> <tbody id="TB"> <tr> <td>1</td> <td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> </tr> <tr> <td>2</td> <td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> </tr> <tr> <td>3</td> <td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> </tr> </tbody> </table> <script> function Add(){ var TB = document.getElementById('TB'); var TB_list = document.getElementById('TB').children; var TB_list_lenght = TB_list.length; var add_line_tr = document.createElement('tr'); var add_line_td = document.createElement('td'); var input_1 = document.createElement('input'); input_1.type = 'text'; add_line_td.appendChild(input_1); add_line_tr.appendChild(add_line_td); //add_line_tr.innerHTML = `<td>${TB_list_lenght+1}</td>`+'<td><input type="text"></td>'+'<td><input type="text"></td>'+'<td><input type="text"></td>' TB.appendChild(add_line_tr); //從最後一行添加 //TB.insertBefore(add_line_tr,TB_list[TB_list.length]); //指定位置添加 } function Clean(){ var TB = document.getElementById('TB'); var TB_list = document.getElementById('TB').children; var TB_list_lenght = TB_list.length; if(TB_list_lenght > 3){ TB.removeChild(TB_list[TB_list_lenght-1]) } } </script> </body> </html>
c.複製和移動標籤
xxx.appendChild(obj) 將obj標籤節點移動到xxx節點 xxx.cloneNode(true) 複製xxx節點以及內部節點 xxx.cloneNode() 複製xxx節點(不復制內部內部節點)
例子:標籤操作之移動和拷貝
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>標籤操作之移動和拷貝</title> </head> <body> <div id="h1" style="background: burlywood;width: 100%;height: 50px"> <a href="#">移動</a> <a href="#">複製</a> </div> <div id="h2"> <div>aaa</div> <div>bbb</div> </div> <script> var obj = document.createElement('a') obj.textContent = 'obj' var h1 = document.getElementById('h1'); var h2 = document.getElementById('h2'); h2.appendChild(h1); //移動到h2裏面 var h3 = h1.cloneNode(); //只是複製外層標籤,裏面不復制 h3.appendChild(obj); h3.style.backgroundColor = 'red'; var h4 = h1.cloneNode(true); //將裏面外面都複製 h2.appendChild(h3); h2.appendChild(h4) </script> </body> </html>
6、高度操作
height_operate.offsetParent //父定位標籤 height_operate.scrollTop //滾動條距離頂部的高度 height_operate.scrollHeight //文檔的高度+padding高度 height_operate.clientTop //邊框的高度:bord的高度 height_operate.clientHeight //可見方框的高度+padding,不包含border height_operate.offsetTop //當前標籤距離'頂部'的的高度 注意:這是相對位置,要看position height_operate.offsetHeight //可見範圍的文檔高度+padding+bord
注意:height_operate是節點
例子:高度操作
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>高度操作</title> <style> *{margin: 0;padding: 0} .Height_operate{width: 700px;height: 450px;margin: 0 auto;border: 4px solid peru;overflow: auto;padding: 10px;position: relative} </style> </head> <body> <div style="height: 20px;background: orange"></div> <div style="border: 4px solid black;padding: 20px;position: absolute"> <div id="height_operate" class="Height_operate"> <div class="content" style="height: 1000px;background: rgba(0,0,0,0.2);"> <div style="height: 80%;background: pink">內容(以上是padding)</div> </div> </div> </div> <script> var height_operate = document.getElementById('height_operate') console.log(height_operate.scrollTop); //滾動條距離頂部的高度 console.log(height_operate.scrollHeight); //文檔的高度+padding高度 console.log(height_operate.clientTop); //邊框的高度:bord的高度 console.log(height_operate.clientHeight); //可見方框的高度+padding,不包含border console.log(height_operate.offsetTop); //當前標籤距離'頂部'的的高度 注意:這是相對位置,要看position console.log(height_operate.offsetHeight); //可見範圍的文檔高度+padding+bord </script> </body> </html>
例子:回到頂部
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>回到頂部</title> <style> .Go_Top{position: fixed;right: 20px;bottom: 50px;width: 40px;height: 40px;background: rgba(0,0,0,0.3);cursor: pointer;z-index: 1} .Go_Top_Change{position: fixed;right: 20px;bottom: 50px;width: 40px;height: 40px;background: rgba(0,0,0,0.6);visibility: hidden;z-index: 2;text-align: center;line-height: 19px} .Go_Top:hover .Go_Top_Change{ visibility: visible; } .Hide{display: none} </style> </head> <body onscroll="Get_Height_Scroll()"> <div style="height: 2000px"></div> <div class="Go_Top Hide" id="go_top"> <div class="Go_Top_Change" onclick="Go_Top()">回到頂部</div> </div> <script> function Get_Height_Scroll(){ var height_scroll = document.body.scrollTop; var go_top = document.getElementById('go_top'); if(height_scroll > 100){ go_top.classList.remove('Hide') }else { go_top.classList.add('Hide') } } function Go_Top(){ document.body.scrollTop = 0; } </script> </body> </html>
例子:滾動菜單
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>滾動菜單</title> <style> *{margin: 0;padding: 0} body{background: #DDDDDD} li {list-style-type:none;text-align: center} .w{margin: 0 auto} .bolder{font-weight: bolder;background: #27a9e3} .fixed{position: fixed;top: 20px} .bg_head{height: 45px;background: #0f5179} .bg_content{width: 960px;background: white;height: 2000px} .bg_content .menu{width: 200px;float: left} .bg_content .content{width: 758px;height: 100%;border:1px solid #000000;float: right;text-align: center} </style> </head> <body onscroll="Scroll()"> <div class="bg_head" ></div> <div class="bg_content w"> <div class="menu" id="Menu"> <ul> <li style="position: relative;left: 0"><h2 style="line-height: 60px;" id="menu_contents">目  錄</h2></li> </ul> <ul style="line-height: 30px" id="menu_chapter"> <li >第一章</li> <li>第二章</li> <li>第三章</li> </ul> </div> <div class="content" id="content"> <div style="height: 500px"><h2>目  錄</h2></div> <div style="height: 1400px">第一章</div> <div style="height: 50px">第二章</div> <div style="height: 50px">第三章</div> </div> </div> <script> function Scroll(){ var scroll_top = document.body.scrollTop; var menu = document.getElementById('Menu'); var content_charen_list = document.getElementById('content').children; var menu_li = menu.getElementsByTagName('li'); if(scroll_top > 80){ menu.classList.add('fixed') }else { menu.classList.remove('fixed') } for(var i=0;i<content_charen_list.length;i++){ var content_item = content_charen_list[i]; var offset_top = content_item.offsetTop; var offset_height = content_item.offsetHeight; var top_count = offset_height + offset_top; for(var item=0;item<menu_li.length;item++){ if(scroll_top>offset_top && scroll_top<top_count) { menu_li[i].className = 'bolder' } } } } </script> </body> </html>
7、提交表單
document.geElementById('form').submit()
例子:提交表單
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>form提交</title> </head> <body > <!--搜狗的:https://www.sogou.com/web?--> <form action="https://www.baidu.com/s?" id="Form" method="get"> <input type="text" name="wd"> <input type="submit" value="提交"> <input id="button" type="button" value="button" onclick="Button()"> </form> <script> function Button(){ document.getElementById('Form').submit(); } </script> </body> </html>
8、其他操作
console.log 輸出框 alert 彈出框 confirm 確認框 // URL和刷新 location.href 獲取URL location.href = "url" 重定向 location.reload() 重新加載 // 定時器 setInterval 多次定時器:跑馬燈有例子 clearInterval 清除多次定時器 setTimeout 單次定時器 clearTimeout 清除單次定時器
例子:驗證碼60s倒計時
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="../statics/js/jquery-1.12.4.js"></script> <script type="text/javascript"> var countdown=60; function settime(obj) { if (countdown == 0) { obj.removeAttribute("disabled"); obj.value="免費獲取驗證碼"; countdown = 60; return; } else { obj.setAttribute("disabled", true); obj.value="重新發送(" + countdown + ")"; countdown--; } setTimeout(function() { settime(obj) } ,1000) } </script> <body> <input type="button" id="btn" value="免費獲取驗證碼" onclick="settime(this)" /> </body> </html>
補充:遞歸(自己調用自己)
例子:跑馬燈
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="str_one" style="height: 150px; color: red; font-size: 50px; text-align: center; line-height: 150px"><b> 瓜子花生款泉水,抽菸喝酒大保健 </b></div> <script> setInterval( function () { str = document.getElementById("str_one"); str_text = str.innerText; first_char = str_text[0]; sub_char = str_text.slice(1,str_text.length); new_str = sub_char + first_char; str.innerText = new_str; },500); </script> </body> </html>
例子:定時器之刪除和恢復簡單例子
<!DOCTYPE html> <html > <head> <title>定時器</title> <meta charset="utf-8"> <style> .hide{display: none} </style> </head> <body> <input type="button" value="刪除" onclick="show_tips()" > <input type="button" value="恢復文件" id="delect_repeal" class="hide" onclick="stop_delect()"> <div id="delect_tips" class="hide">5s後徹底刪除文件</div> <script> function show_tips(){ delect_tips =document.getElementById('delect_tips'); delect_repeal = document.getElementById('delect_repeal'); delect_repeal.classList.remove('hide'); delect_tips.classList.remove('hide'); //setTimeout(hide_tips,5000) item = setTimeout(hide_tips,5000) } function hide_tips(){ delect_repeal.className='hide'; delect_tips.className='hide'; } function stop_delect(){ clearTimeout(item) } </script> </body> </html>
參考:http://www.cnblogs.com/suoning/p/5656922.html