0級(jí)事件處理
用的最多的就是onload了
<script>
//內(nèi)嵌模式()
<body onload="alert("工大學(xué)子")">
<body onload="hello();">
注意小括號(hào)引號(hào)這類的 和下面的不同
或者在js里的
</script>
<script>
//傳統(tǒng)模式(推薦)
window.onload=function(){
......
alert(“工大學(xué)子”);
}
//window.onload=hello();
</script>
結(jié)束function 終止事件
function() doSomething{
return false;
}
提醒一下function name(){。。。}這是function的格式 name的位置還有小括號(hào)的位置......
指定多個(gè)函數(shù)
<body onload="hello();hello2()">
傳統(tǒng)模式
function(){
var helloString="hello you ";
alert(helloString);
hello2();
在這里調(diào)用第二個(gè)
}
除了onload 還有onmouseover onmouseout onclick
這個(gè)好像用的更多 但提醒一下css的偽類hover有時(shí)候用的更方便一點(diǎn)
event對象
例:window.event.screenX
我們可以通過event干好多事情
我記住的就screenX還有screenY 指事件觸發(fā)時(shí)屏幕的x y值;
clientX客戶端當(dāng)前x
clientY客戶端當(dāng)前y
有什么區(qū)別自己回去查
event的兼容性
ie是
function onmouseover(){
。。。
//小括號(hào)里沒有東西 ie默認(rèn)是通過程序訪問window對象其包含的數(shù)據(jù)也會(huì)相應(yīng)填充
}
docunment.onmouseover=onmouseover
其他瀏覽器(基于netscape)是:
function onmouseover(theEvent){
//括號(hào)里有東西。。。
}
docunment.onmouseover=onmouseover
所以考慮兼容用下面的方法
<script>
function onmousedown(nsEvent){
var theEvent=nsevent?nsevent:window.event;
//看看nsEvent是否被定義
var locString="x="+theEvent.screenX+"y="+theEvent.screenY;
alert(locString);
}
</script>
document.onmousedown=onmousedown;
事件冒泡
就是你給一個(gè)爺爺輩父親輩兒子輩的三個(gè)div分別寫三個(gè)一樣的觸發(fā)時(shí)間假設(shè)都是onclick 你會(huì)發(fā)現(xiàn)當(dāng)你點(diǎn)擊兒子時(shí)爺爺和爸爸的onclick都被觸發(fā)
不理解的回去寫三個(gè)嵌套的div試試;
取消冒泡機(jī)制
ie:cancelBubble
mozilla:stopPropagation
function stopEvent(evnt){
if(evnt.stopPropagation){
evnt.stopPropagation}
else{
evnt.cancelBubble=true;
}
}
document.getElementById("ididid").onmouseover=function(evnt){
var theEvent=evnt?evnt:window.event;
alert("鬼一樣的ie");
stopEvent(theEvent);
//調(diào)用上面寫的stopEvent函數(shù);
}
this
經(jīng)常見
當(dāng)前調(diào)用的函數(shù)或方法的所有者
對全局函數(shù)就是window
事件捕獲一個(gè)用途
在html里你在寫一個(gè)id為myid的一個(gè)input 就會(huì)實(shí)現(xiàn)打開網(wǎng)頁 這個(gè)input自動(dòng)獲得焦點(diǎn)。。。。。百度的效果
window.onload=myFunction;
function myFunction(){
document.getElementById(""myid").focus();
}