天天看點

JavaScriptwindow(六)

window對象(Dom中的一個頂級對象)

window對象代表目前浏覽器視窗。

使用window對象的屬性、方法的時候可以省略window。

比如:

window.alert(‘hello');可以省略成alert(‘hello');

window.document可以直接寫document

能不寫window就不要寫,這樣可以減少js檔案的位元組數。

window對象的方法

window.alert(‘大家好!’);//彈出警告對話框

window.confirm(‘确定要删除嗎?’);//确定、取消對話框,傳回true或false;

window.navigate(url);//将網頁重新導航到url,隻支援IE、Opera11.6,建議使用window.location.href=‘url’;//支援大多數浏覽器

window.setInterval(code,delay)//每隔一段時間執行指定的代碼(類似于winForm中的Timer控件。)

第一個參數:指定的代碼字元串

第二個參數:時間間隔(毫秒數)

var intervalId=setInterval(“alert(‘hello’);”,1000);

例:讓文本框的數值自增

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

   <title></title>

  <meta charset="utf-8" />

   <script type="text/javascript">

       setInterval(function ()

       {undefined

           var num = txt.value;

           num = parseInt(num) + 1;

           txt.value = num;

       }, 1000)

   </script>

</head>

<body>

  <input type="text" id="txt" value="1"/>

</body>

</html>

window.clearInterval(intervalId);//停止計時器

clearInterval()取消setInterval的定時執行,相當于Timer中的Enabled=False。因為setInterval可以設定多個定時,是以clearInterval要指定清除那個定時器的辨別,即setInterval的傳回值。

注:<input type="button" value="滾動" οnclick="setInterval('scroll()', 500)" />

每調用一次setInterval都會産生一個新的定時器,并且舊的不會自動停止。是以看起來好像“越跑越快”!

clearInterval(setInterval('scroll()', 500)),錯,不會停止原先的定時器,因為setInterval就産生一個新的定時器,剛産生就被clear

應用舉例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

   <title>北京歡迎你</title>

       var timerId;

       function scroll() {undefined

           var title = document.title;

           var lastCh = title.charAt(title.length - 1); //容易錯

           var leftStr = title.substring(0, title.length - 1);

           document.title = lastCh + leftStr;

       }

       //每調用一次setInterval都會産生一個新的定時器,并且舊的不會自動停止。是以看起來好像“越跑越快”!

<input type="button" value="滾動" οnclick="if(timerId){clearInterval(timerId);}timerId=setInterval('scroll()', 500)" />

<input type="button" value="停止(錯誤寫法)" οnclick="clearInterval(setInterval('scroll()', 500))" />

<input type="button" value="停止" οnclick="clearInterval(timerId)" />

例:利用定時器實作跑馬燈效果.

   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

   <title>0123456789</title>

   <meta charset="utf-8" />

       var dir = "left";

       setInterval(function () {undefined

           var first;

           var last;

           if (dir == 'left') {undefined

               first = title.substr(0, 1);

               last = title.substr(1);

           } else {undefined

               first = title.substring(0, title.length - 1);

               last = title.substring(title.length - 1, title.length);

           }

           document.title = last + first;

       function setDir(d)

           dir = d;

   <input id="Button1" type="button" value="向左" οnclick="setDir('left')" />

   <input id="Button2" type="button" value="向右" οnclick="setDir('right')"/>

body、document對象的事件

onload(頁面加載後觸發)

網頁加載完畢時觸發,浏覽器是一邊下載下傳文檔、一邊解析執行,可能會出現JavaScript執行時需要操作某個元素,這個元素還沒有加載,如果這樣就要把操作的代碼放到body的onload事件中,或者可以把JavaScript放到元素之後。元素的onload事件是元素自己加載完畢時觸發,body onload才是全部加載完成。

window.控件Id(不建議使用)

document.getElementById(“控件Id”);(推薦)

除了屬性之外,當然還有通用的HTML元素的事件:onclick(單擊)、ondblclick(輕按兩下)、onkeydown(按鍵按下)、onkeypress(點選按鍵)、onkeyup(按鍵釋放)、onmousedown(滑鼠按下)、onmousemove(滑鼠移動)、onmouseout(滑鼠離開元素範圍)、onmouseover(滑鼠移動到元素範圍)、onmouseup(滑鼠按鍵釋放)、oncontextmenu(在浏覽器中單擊滑鼠右鍵顯示”右鍵菜單”時觸發)等。

window對象的屬性

window.location對象:

window.location.href=‘’;//重新導航到新頁面,可以取值,也可以指派。

window.location.reload();//重新整理目前頁

window.event是IE下非常重要的屬性,用來獲得發生事件時的資訊,事件不局限于window對象的事件,所有元素的事件都可以通過event屬性取到相關資訊。類似于winForm中的e(EventArgs)。//相容IE、Chrome,不相容FF(用event參數)。

window.event.altKey屬性,bool類型,表示事件發生時是否按下了alt鍵。類似的還有ctrlKey,shiftKey。示範:<input type="button" value="點選" οnclick="if(event.altKey){alert('Alt點選')}else{alert('普通點選')}" /> ;

clientX、clientY 發生事件時滑鼠在客戶區的坐标;screenX、screenY 發生事件時滑鼠在螢幕上的坐标;offsetX、offsetY 發生事件時滑鼠相對于事件源(比如點選按鈕時觸發onclick)的坐标。

<script type="text/javascript">

       document.onmousemove = function ()

       {//滑鼠在文檔上的位置。

           // document.title = window.event.clientX + "==" + window.event.clientY;

           //滑鼠早螢幕上的位置。

           //document.title = window.event.screenX + '==' + window.event.screenY;

           //相對事件源的位置。

           document.title = window.event.offsetX + '==' + window.event.offsetY;

(window.event.returnValue)returnValue屬性,如果将returnValue設定為false,就會取消預設行為的處理。在超連結的onclick裡面禁止通路href的頁面。在表單校驗的時候禁止送出表單到伺服器,防止錯誤資料送出給伺服器、防止頁面重新整理。(οnsubmit="window.event.returnValue=false;")

window.event.returnValue不相容火狐浏覽器

例1:送出表單時,驗證使用者名是否為空,為空則取消送出動作。

<html xmlns="http://www.w3.org/1999/xhtml">

       function btn_click() {undefined

           var txt = document.getElementById("txt").value;

           if (txt.length == 0) {undefined

               alert("請輸入使用者名!");

document.getElementById("txt").focus();//文本框獲得光标

               window.event.returnValue = false;

   <form action="HTMLPage2.htm">

   <input id="txt" type="text" />

   <br />

   <input id="Submit1" type="submit" value="submit" οnclick="btn_click()" />

   </form>

例2:判斷超連結能否跳轉

       function link_click(a) {undefined

           if (a) {undefined

           else {undefined

               alert("無權限")

   <a id="link" href="HTMLPage2.htm" οnclick="link_click(0)">hjijiodhoih</a>

FireFox:e. preventDefault();取消事件的預設動作。

直接寫return false;IE、FF、Chrome都可以。需要動态注冊事件才可以實作。

例1: <html xmlns="http://www.w3.org/1999/xhtml">

       window.onload = function() {undefined

           document.getElementById("Submit1").onclick = function() {undefined

               var txt = document.getElementById("txt").value;

               if (txt.length == 0) {undefined

                   alert("請輸入使用者名!");

                   document.getElementById("txt").focus(); //文本框獲得光标

                   return false;

               }

   <input id="Submit1" type="submit" value="submit" />

例2:讓超連結無效

       window.onload = function() {

           document.getElementById("link").onclick = function() {

               return false;

   <a id="link" href="HTMLPage2.htm">hjijiodhoih</a>

//在FF下的寫法

       function bodyClickHandlerOnFF(e) {

           if (e.altKey) {

               alert('按下alt鍵');

           } else {

               alert('普通點選!');

<body οnclick=“bodyClickHandlerOnFF(event);">

//在IE下的寫法

       function bodyClickHandler() {

           if (window.event.altKey) {

               alert('press alt key');

               alert('normal click');

<body οnclick=“bodyClickHandler();">

=========================相容的寫法===============================

<script type="text/javascript">

       document.body.onmousemove = function () {

           if (window.event) {

               document.title = '(' + window.event.clientX + ',' + window.event.clientY + ')';

               document.title = '(' + arguments[0].clientX + ',' + arguments[0].clientY + ')';

</script>

window.event的屬性(接上頁):

srcElement:獲得事件源對象。幾個按鈕共享一個事件響應函數用。****_click(object sender,EventArgs e)//IE、Chrome支援。見備注1。//FF下用e.target;

IE下:

function MyEventHandler() {

           var obj = window.event.srcElement;

           alert(obj.value);

}

<input type="button" value="click me!" οnclick="MyEventHandler();" />

FF下:

       function MyEventHandlerFF(e) {

           var obj = e.target;

<input type="button" value="FF Click me" οnclick="MyEventHandlerFF(event);" />

//IE and FF

function TNB(e) {

           if (e.target) {

               alert(e.target.value);

           } else if (e.srcElement) {

           alert(e.srcElement.value);

 }

button,發生事件時滑鼠按鍵,IE:1為左鍵,2為右鍵,4中滑輪//要測試event.button的值的時候,請在onmousedown事件中測試。在onclick事件中隻能識别滑鼠左鍵的單擊。不同浏覽器傳回值可能不一樣。 (不同浏覽器值不一樣)

             <script type="text/javascript">    

             function mousedown()

             {undefined

                alert(event.button);

             }

 <input id="Button1" type="button" value="/" οnmοusedοwn="mousedown()"/>

除IE浏覽器外,其他浏覽器在綁定事件處理函數時,有一個預設的參數即event對象。

(*)screen對象,擷取螢幕的資訊:

alert("分辨率:" + screen.width + "*" + screen.height);

       if (screen.width < 1024 || screen.height < 768) {undefined

          alert("分辨率太低!");

clipboardData對象,對粘貼闆的操作。//隻支援IE,FF參考資料

setData("Text",val),設定粘貼闆中的值。

例:

<script type="text/javascript">    

       function f1()

           var t = document.getElementById("txt").value;

           window.clipboardData.setData("text", t);

</script>

   <input id="txt" type="text" value="http://www.qiushibaike.com"/>

   <input id="Button1" type="button" value="複制" οnclick="f1()"/>

getData(“Text”)讀取粘貼闆的值,傳回值為粘貼闆中的内容;

clearData(“Text”)清空粘貼闆;

案例:複制位址給友好。見備注。

當複制的時候body的oncopy方法被觸發,直接return false就是禁止複制。<body οncοpy="alert('禁止複制!');return false;"

很多元素也有oncopy(複制)、onpaste(粘貼)事件:oncut

案例:禁止粘貼帳号。

<input type="text" id="num1" οncοpy="alert('禁止複制'); return false;" οndrag="return false"/><br/>

 <input type="text" οnpaste="return false;" οndrag="return false"/>

案例:在網站中複制文章的時候,為了防止那些”拷貝黨”不添加文章來源,代碼:

       function ff()

           var t = clipboardData.getData("text");

           t = t + "<br/> 版權:www.srtc.org.cn";

           clipboardData.setData("text", t);

<body οncοpy="setTimeout('ff()',100)">

   <span>shiusdhfiusdhuihfiusdh</span>

使用者複制動作發生0.1秒以後再去改粘貼闆中的内容。100ms隻是一個經常取值,寫1000、10、50、200……都行。不能直接在oncopy裡修改粘貼闆。不能直接在oncopy中執行對粘貼闆的操作,是以設定定時器,0.1秒以後執行,這樣就不再oncopy的執行調用棧上了。

history操作曆史記錄。

window.history.back()後退;window.history.forward()前進。

window.history.go(-1)後退、window.history.go(1)前進

document屬性:

document屬性是window對象中最複雜的屬性。

因為使用window對象成員的時候可以省略window.,是以一般直接寫document。

document的方法:

write();//向文檔中寫入内容。writeln(),和write差不多,隻不過最後添加一個回車。在onclick等事件中寫的代碼會沖掉頁面中的内容,隻有在頁面加載過程中write才會與原有内容融合在一起。writeln()是在源代碼裡面換行。與<br/>不一樣。

document.write()經常在廣告代碼、整合資源代碼中被使用。

内容聯盟、廣告代碼、cnzz,不需要被首頁面的站長去維護内容,隻要被嵌入的js内容提供商修改内容,顯示的内容就變了。例:

write經常在廣告代碼、整合資源代碼中被使用

廣告代碼的例子:在

http://heima8.com/

注冊一個賬戶(測試用 賬戶名:itcast0710 密碼:123456),申請一個廣告代碼,然後放到頁面中

整合資源的例子:百度新聞

http://news.baidu.com/newscode.html

百度新聞代碼相當于頁面中嵌入另外一個網站的js檔案,js檔案就是一個大的write語句,這樣的好處就是首頁面不用寫死内容,被嵌入的js内容變了嵌入的内容就變了。

腳本的好處:

1.自動執行

2.動态生成。

=================example==================

       var reffer = "";

       var url = "";

       if (window.parent != window.self) {undefined

           try { reffer = parent.document.referrer; }

           catch (err) { reffer = document.referrer; }

           try { url = parent.document.location; }

           catch (err) { url = document.location; }

       } else { reffer = document.referrer; url = document.location; }

       document.writeln("<iframe marginwidth='0' marginheight='0' frameborder='0' bordercolor='#000000' scrolling='no' src='http://pv.heima8.com/index.php?p=126292971&b=100002856&itemid1=107075271&reffer=" + escape(reffer) + "&url=" + escape(url) + "' width='468' height='60'></iframe>");

(使用pre标簽看write()與writeln()的差別,效果)。例:

   document.write('<pre>');

document.write('1');

document.writeln('2');

document.write('3');

document.write('</pre>');

最基本的DOM周遊示範。

//周遊直接子節點,如需獲得所有節點。需要放在頁面的最後測試(或者是在onload裡面,否則頁面還沒有加載完畢。)

var objHtml = document.documentElement;

for (var i = 0; i < objHtml.childNodes.length; i++) {undefined

  alert(objHtml.childNodes[i].nodeName);

getElementById(), (非常常用),根據元素的Id獲得對象,網頁中id不能重複。也可以直接通過元素的id來引用元素,但是有有效範圍、form1.textbox1之類的問題(當元素放在form中的時候(在html頁面中需要通過form.元素id)),是以不建議直接通過id操作元素,而是通過getElementById。

注:如果在網頁中有id重複的元素,那麼getElementById()獲得的是

           //第一id為指定id的元素,而不是數組

           var txtctrl = document.getElementById('txt1');

getElementsByName(),根據元素的name獲得對象,由于頁面中元素的name可以重複,比如多個RadioButton的name一樣,是以getElementsByName傳回值是對象數組。

getElementsByTagName(),獲得指定标簽名稱的元素數組,比如getElementsByTagName(“p”)可以獲得所有的<p>标簽。*表示所有标簽。

此處切忌不要使用forin循環(forin循環循環的是鍵值對,不是對象本身。)。(問題多多:radio時有相同的key,第一個key是length等等。。)建議:使用for循環案例:實作checkbox的全選,反選

案例:點選一個按鈕,被點選的按鈕顯示“嗚嗚”,其他按鈕顯示“哈哈”。

第一種寫法

       function g() {undefined

           var strls = document.getElementsByName("11");

           for (var i = 0; i < strls.length; i++) {undefined

               strls[i].value = "哈哈";

           window.event.srcElement.value = "嗚嗚!!"

   <input id="Button1" type="button" name="11" value="button" οnclick="g()" />

   <input id="Button2" type="button" name="11" value="button" οnclick="g()" />

   <input id="Button3" type="button" name="11" value="button" οnclick="g()" />

   <input id="Button4" type="button" name="11" value="button" οnclick="g()" />

第二種寫法

       window.onload = function () {undefined

           var inputs = document.getElementsByTagName("input");

           for (var i = 0; i < inputs.length; i++) {undefined

               if (inputs[i].type == "button") {undefined

                   inputs[i].onclick = function () {undefined

                       for (var i = 0; i < inputs.length; i++) {undefined

                           if (inputs[i].type == "button") {undefined

                               inputs[i].value = "哈哈";

                           }

                       }

                       //觸發事件的對象

                       event.srcElement.value = "嗚嗚";

                   }

   <input type="button" value="哈哈" /><br />

   <input type="text" value="" /><br />

練習:加法電腦。兩個文本框中輸入數字,點選【=】按鈕将相加的結果放到第三個文本框中。

   <input type="text" id="num1" />+<input type="text" id="num2" />

   <input type="button" οnclick="calc()" value="=" /><input type="text" id="num3" />

       function calc() {undefined

           var s1 = document.getElementById("num1").value;

           var s2 = document.getElementById("num2").value;

           var i3 = parseInt(s1) + parseInt(s2);

           document.getElementById("num3").value = i3;

案例:十秒鐘後協定文本框下的注冊按鈕才能點選,時鐘倒數。(btn.disabled = “” ,讓元素可用。disabled=disabled,為不可用)disabled=true;

       var count = 10;

       var tmrId = setInterval("test()", 1000);

       function test() {undefined

           var btn = document.getElementById("btn");

           if (count > 0) {undefined

               btn.value = "請仔細閱讀(" + count + ")秒";

               count--;

           btn.value = "同意";

           btn.disabled = false;

           clearInterval(tmrId);

           test();

   <input id="btn" type="button" value="請仔細閱讀(10)秒" disabled="disabled" />

練習:圖檔浏覽器。

           var ul = document.getElementById("mv");

           //擷取ul中的a标簽

           var links = ul.getElementsByTagName("a");

           for (var i = 0; i < links.length; i++) {undefined

               links[i].onclick = function () {//注冊事件

                   var href = event.srcElement.href;

                   document.getElementById("i1").src = href;

   <ul id="mv">

       <li><a href="images/1.jpg">美女1</a></li>

       <li><a href="images/2.jpg">美女2</a></li>

       <li><a href="images/3.jpg">美女3</a></li>

       <li><a href="images/4.jpg">美女4</a></li>

   </ul>

   <img id="i1" src="" />