易被忽视的js事件问题总结(2)

 三、IE和DOM区别
                         DOM                                IE
获取目标        event.target                     event.srcElement
获取字符代码 event.charCode              event.keyCode
阻止默认行为 event.prevetDefault()      event.returnvalue=false
冒泡                event.stopPropagation() event.cancelBubble=true

关于阻止默认行为,比如,当用户右击鼠标时,如果你不想菜单弹出,则可以使用阻止默认行为:

document.body.oncontextmenu=function(event) { if(isIE) { var oEvent=window.event; oEvent.returnValue=false; //也可以直接是return false;阻止默认行为 } else { oEvent.preventDefault(); } }

四、鼠标事件

<p>use your mouse to click and double click the red square</p> <div onmousedown="handleEvent(event)" onmouseup="handleEvent(event)" ondblclick="handleEvent(event)" > </div> <p><textarea rows="5" cols="45"></textarea></p> <!--检测键盘事件--> <p><input type="text" onkeydown="handle(event)" onkeypress="handle(event)" onkeyup="handle(event)" ></p> <p><textarea rows="10" cols="45"></textarea></p>

js文件如下:

function handleEvent(event) { var oText=document.getElementById('txt1'); oText.value+= "\n"+event.type; oText.value+= "\n target is "+(event.srcElement||event.target).id; oText.value+="\n at ("+event.clientX+","+event.clientY+")in the client"; oText.value+="\n at ("+event.screenX+","+event.screenY+")in the client"; oText.value+="\n button down is"+event.button; var arrKeys=[]; oText.value+="\n relatedTarget is"+event.relatedTarget.tagName; //event.relatedTarget.tagName可以判断鼠标的来源和出处 } function handle(event) { var oText2=document.getElementById('txt2'); oText2.value+="\n"+event.type; var arrKeys=[]; if(event.shiftKey){arrKeys.push("Shift");} if(event.ctrlKey){arrKeys.push("Ctrl");} if(event.altKey){arrKeys.push("Alt");} oText2.value+="\n keydown is "+arrKeys; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzpfgj.html