- 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 ()
{
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" >
<head>
<title>北京歡迎你</title>
<script type="text/javascript">
var timerId;
function scroll() {
var title = document.title;
var lastCh = title.charAt(title.length - 1); //容易錯
var leftStr = title.substring(0, title.length - 1);
document.title = lastCh + leftStr;
}
//每調用一次setInterval都會產生一個新的定時器,並且舊的不會自動停止。所以看起來好像“越跑越快”!
</script>
</head>
<body>
<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)" />
</body>
</html>
例:利用定時器實現跑馬燈效果.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>0123456789</title>
<meta charset="utf-8" />
<script type="text/javascript">
var dir = "left";
setInterval(function () {
var title = document.title;
var first;
var last;
if (dir == 'left') {
first = title.substr(0, 1);
last = title.substr(1);
} else {
first = title.substring(0, title.length - 1);
last = title.substring(title.length - 1, title.length);
}
document.title = last + first;
}, 1000)
function setDir(d)
{
dir = d;
}
</script>
</head>
<body>
<input id="Button1" type="button" value="向左" οnclick="setDir('left')" />
<input id="Button2" type="button" value="向右" οnclick="setDir('right')"/>
</body>
</html>
- 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;
}
</script>
- (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">
<head>
<title>北京歡迎你</title>
<script type="text/javascript">
function btn_click() {
var txt = document.getElementById("txt").value;
if (txt.length == 0) {
alert("請輸入用戶名!");
document.getElementById("txt").focus();//文本框獲得光標
window.event.returnValue = false;
}
}
</script>
</head>
<body>
<form action="HTMLPage2.htm">
<input id="txt" type="text" />
<br />
<input id="Submit1" type="submit" value="submit" οnclick="btn_click()" />
</form>
</body>
</html>
例2:判斷超鏈接能否跳轉
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>北京歡迎你</title>
<script type="text/javascript">
function link_click(a) {
if (a) {
}
else {
alert("無權限")
window.event.returnValue = false;
}
}
</script>
</head>
<body>
<a id="link" href="HTMLPage2.htm" οnclick="link_click(0)">hjijiodhoih</a>
</body>
</html>
- FireFox:e. preventDefault();取消事件的默認動作。
- 直接寫return false;IE、FF、Chrome都可以。需要動態註冊事件纔可以實現。
例1: <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>北京歡迎你</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById("Submit1").onclick = function() {
var txt = document.getElementById("txt").value;
if (txt.length == 0) {
alert("請輸入用戶名!");
document.getElementById("txt").focus(); //文本框獲得光標
return false;
}
}
}
</script>
</head>
<body>
<form action="HTMLPage2.htm">
<input id="txt" type="text" />
<br />
<input id="Submit1" type="submit" value="submit" />
</form>
</body>
</html>
例2:讓超鏈接無效
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>北京歡迎你</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById("link").onclick = function() {
return false;
}
}
</script>
</head>
<body>
<a id="link" href="HTMLPage2.htm">hjijiodhoih</a>
</body>
</html>
//在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');
} else {
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 + ')';
} else {
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;
alert(obj.value);
}
<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()
{
alert(event.button);
}
</script>
<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) {
alert("分辨率太低!");
}
例:
<script type="text/javascript">
function f1()
{
var t = document.getElementById("txt").value;
window.clipboardData.setData("text", t);
}
</script>
<body>
<input id="txt" type="text" value="http://www.qiushibaike.com"/>
<input id="Button1" type="button" value="複製" οnclick="f1()"/>
</body>
-
- 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"/>
-
- 案例:在網站中複製文章的時候,爲了防止那些”拷貝黨”不添加文章來源,代碼:
<script type="text/javascript">
function ff()
{
var t = clipboardData.getData("text");
t = t + "<br/> 版權:www.srtc.org.cn";
clipboardData.setData("text", t);
}
</script>
<body οncοpy="setTimeout('ff()',100)">
<span>shiusdhfiusdhuihfiusdh</span>
</body>
用戶複製動作發生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==================
<script type="text/javascript">
var reffer = "";
var url = "";
if (window.parent != window.self) {
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>");
</script>
-
-
- (使用pre標籤看write()與writeln()的區別,效果)。例:
-
<script type="text/javascript">
document.write('<pre>');
document.write('1');
document.writeln('2');
document.write('3');
document.write('</pre>');
</script>
-
-
- 最基本的DOM遍歷演示。
-
//遍歷直接子節點,如需獲得所有節點。需要放在頁面的最後測試(或者是在onload裏面,否則頁面還沒有加載完畢。)
var objHtml = document.documentElement;
for (var i = 0; i < objHtml.childNodes.length; i++) {
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的全選,反選
-
- 案例:點擊一個按鈕,被點擊的按鈕顯示“嗚嗚”,其他按鈕顯示“哈哈”。
第一種寫法
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>北京歡迎你</title>
<script type="text/javascript">
function g() {
var strls = document.getElementsByName("11");
for (var i = 0; i < strls.length; i++) {
strls[i].value = "哈哈";
}
window.event.srcElement.value = "嗚嗚!!"
}
</script>
</head>
<body>
<input id="Button1" type="button" name="11" value="button" οnclick="g()" />
<br />
<input id="Button2" type="button" name="11" value="button" οnclick="g()" />
<br />
<input id="Button3" type="button" name="11" value="button" οnclick="g()" />
<br />
<input id="Button4" type="button" name="11" value="button" οnclick="g()" />
</body>
</html>
第二種寫法
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
window.onload = function () {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "button") {
inputs[i].onclick = function () {
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "button") {
inputs[i].value = "哈哈";
}
}
//觸發事件的對象
event.srcElement.value = "嗚嗚";
}
}
}
}
</script>
</head>
<body>
<input type="button" value="哈哈" /><br />
<input type="button" value="哈哈" /><br />
<input type="button" value="哈哈" /><br />
<input type="button" value="哈哈" /><br />
<input type="button" value="哈哈" /><br />
<input type="button" value="哈哈" /><br />
<input type="button" value="哈哈" /><br />
<input type="button" value="哈哈" /><br />
<input type="text" value="" /><br />
<input type="text" value="" /><br />
<input type="text" value="" /><br />
<input type="text" value="" /><br />
</body>
</html>
- 練習:加法計算器。兩個文本框中輸入數字,點擊【=】按鈕將相加的結果放到第三個文本框中。
<input type="text" id="num1" />+<input type="text" id="num2" />
<input type="button" οnclick="calc()" value="=" /><input type="text" id="num3" />
function calc() {
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;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>北京歡迎你</title>
<script type="text/javascript">
var count = 10;
var tmrId = setInterval("test()", 1000);
function test() {
var btn = document.getElementById("btn");
if (count > 0) {
btn.value = "請仔細閱讀(" + count + ")秒";
count--;
} else {
btn.value = "同意";
btn.disabled = false;
clearInterval(tmrId);
}
}
window.onload = function() {
test();
}
</script>
</head>
<body>
<input id="btn" type="button" value="請仔細閱讀(10)秒" disabled="disabled" />
</body>
</html>
- 練習:圖片瀏覽器。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
window.onload = function () {
var ul = document.getElementById("mv");
//獲取ul中的a標籤
var links = ul.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].onclick = function () {//註冊事件
var href = event.srcElement.href;
document.getElementById("i1").src = href;
return false;
}
}
}
</script>
</head>
<body>
<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>
<br />
<img id="i1" src="" />
</body>
</html>