DOM基础教程之事件类型

对于用户事件类型而言,最常用的是鼠标、键盘、浏览器。

1.鼠标事件:

DOM基础教程之事件类型

鼠标的事件都频繁使用,下面例子就测试各种鼠标事件

复制代码 代码如下:


<script language="javascript">
            function handle(oEvent) {
                var disp = document.getElementById("display");
                if (window.event) oEvent = window.event; //处理兼容性,获得对象
                disp.innerHTML += "鼠标事件名称:" + oEvent.type + "<br>";
            }
            window.onload = function() {
                var oP = document.getElementById("box");
                oP.onmousedown = handle;
                oP.onmouseover = handle;
                oP.onmouseup = handle;
                oP.onmouseout = handle;
                oP.onclick = handle;
                oP.ondblclick = handle;
            }
        </script>
        <div>
            <div>
                box内容
            </div>
            <p></p>
        </div>

鼠标的键值button测试(附对照表)

DOM基础教程之事件类型

复制代码 代码如下:


<script language="javascript">
            function TestClick(oEvent) {
                var oDiv = document.getElementById("display");
                if (window.event)
                    oEvent = window.event;
                oDiv.innerHTML += oEvent.button; //输出button的值
            }
            document.onmousedown = TestClick;
            window.onload = TestClick; //测试未按下任何键
        </script>
        <div>
            <p></p>
        </div>

2.键盘事件

键盘事件种类不多,仅三种事件。

keydown(按下某键,一直按住会持续触发)

keypress(按下某键并产生字符时触发,即忽略Shift、Alt,ctrl等功能键)

keyup(释放某个键时触发)

键盘监听示例:

复制代码 代码如下:


<script language="javascript">
            function handle(oEvent) {
                if (window.event) oEvent = window.event; //处理兼容性,获得事件对象
                var oDiv = document.getElementById("display");
                oDiv.innerHTML += oEvent.type + "&nbsp;"; //输出事件名称
            }
            window.onload = function() {
                var oTextArea = document.getElementById("textin");
                oTextArea.onkeydown = handle; //监听所有键盘事件
                oTextArea.onkeyup = handle;
                oTextArea.onkeypress = handle;
            }
        </script>
        <div>
            <textarea rows="4" cols="50">
            </textarea>
            <p></p>
        </div>

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

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