zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

JavaScript 各种事件触发总结

2023-02-18 16:46:25 时间

JavaScript 事件绑定

◆键盘鼠标◆

键盘事件: 当键盘接收到按下弹起等按键时,执行操作.

<body onkeypress="keycode()">
    <input type="text" name="text" onkeydown="func_keydown()">
    <input type="text" name="text" onkeyup="func_keyup()">
    <input type="text" name="text" onkeypress="func_keypress()">

    <script type="text/javascript">
        function func_keydown() { alert("你按下了键"); }
        function func_keyup() { alert("你松开了键"); }
        function func_keypress() { alert("你按下并松开"); }
        function keycode(){
            if(window.event.keyCode==32)
            {
                alert("你在body区域按下了空格.");
            }
        }
    </script>
</body>

Resize: 当浏览器窗口或帧的大小发生变化时触发Resize事件.

<body onresize="mesg()">

    <script type="text/javascript">
        function mesg() {
            document.write("窗口大小已被改变了..." + "<br>")
        }
    </script>
</body>

鼠标 Click: 鼠标在一个对象上左键点击触发Click事件,对象包括button,document,checkbox,link,radio,submit.

<body>

    <input type="button" id="button1" value="按钮1" onclick="alert('按钮1被按下了...')">
    <input type="button" id="button2" value="按钮2" onclick="alert('按钮2被按下了...')">
    
    <script type="text/javascript">
    </script>
</body>

MouseDown&MouseUP: 当我们按下鼠标,系统触发MouseDown事件,释放鼠标时自动触发MouseUP事件.

<body>
    <input type="button" value="点我" onmousedown="down()">
    <input type="button" value="点我" onmouseup="up()">
    
    <script type="text/javascript">
        function down() {
            document.write("你按下了按键...")
        }
        function up() {
            document.write("你释放了按键...")
        }
    </script>
</body>

MouseOver&MouseOut: 鼠标指针到达一个对象之上时,触发MouseOver事件,鼠标离开时触发MouseOut事件.

<body>
    <input type="submit" value="鼠标在按钮上" onmouseover="in_over()"></input>
    <input type="submit" value="鼠标离开按钮" onmouseout="out_over()"></input>

    <script type="text/javascript">
        function in_over() {
            alert("鼠标在按钮上...")
        }
        function out_over(){
            alert("鼠标离开按钮...")
        }
    </script>
</body>

OnClick: 通用事件,可以绑定到任何可以操作的标签中,当事件触发后,执行对应的函数体.

<body>
    <input type="button" value="弹窗" onclick="show()">

    <script type="text/javascript">
        function show(){
            alert("触发弹窗一个窗口提示...")
        }
    </script>
</body>

Focus&Blur: 当屏幕上的光标进入对象区域内时触发focus事件,反之当光标离开时触发blur事件.

<body>
    <input onfocus="Focus(this);" onblur="Blur(this);"
    	   id="search" value="请输入关键字" style="color: gray;" />

    <script type="text/javascript">
       function Focus(ths){             //光标来到执行
            ths.style.color = "black";
            if(ths.value == '请输入关键字' || ths.value.trim() == ""){

                ths.value = "";
            }
        }
        function Blur(ths){            //光标离开执行
            if(ths.value.trim() == ""){
                ths.value = '请输入关键字';
                ths.style.color = 'gray';
            }else{
                ths.style.color = "black";
            }
        }
    </script>
</body>

Submit: 通常和form标记配合使用,其作用是用于送出数据,用户在form中输入数据后,点击Sumbit触发自定义函数.

<body>
    <form name="forms" method="post" onsubmit="return check()">
        <input type="text" name="texts" size="20">
        <input type="submit" value="提交">
    </form>

    <script type="text/javascript">
        function check() {
            if(document.forms.texts.value == ""){
                document.forms.focus()
                alert("用户没有输入任何内容...")
                return false
            }else
            {
                alert("用户输入了内容...")
                return true
            }
        }
    </script>
</body>

Submit: 通常和form标记配合使用,其作用是用于送出数据,用户在form中输入数据后,点击Sumbit触发自定义函数.

<body>
    <form action="https://www.baidu.com">
        <input type="text" id="username">
        <input type="submit" value="提交" onclick="return MySub()">
    </form>

    <script type="text/javascript">
        function MySub(){
            var user = document.getElementById("username");
            if(user.value.length > 0){
                alert("编辑框内有数据,允许提交数据..")
                return true;
            }else
            {
                alert("用户名输入不能为空...")
                return false;
            }
        }
    </script>
</body>

Reset: 通常情况下和form标记配合使用,其起到的作用是,当用户完成信息输入后,按下按钮自动清空已经输入的数据.

<body>
    <form name="forms" method="post" >
        <input type="text">
        <input type="password">
        <input type="reset" value="重置" onreset="reset()">
    </form>

    <!--<script type="text/javascript">-->
        <!--function reset(){-->
            <!--alert("内容已经清空了...")-->
            <!--return 1-->
        <!--}-->
    <!--</script>-->
</body>

Change: 当文本区域中的鼠标指针移离该对象时,若对象内容与原来内容不同,则就会触发Change事件.

<body>
    <textarea name="text" rows="3" cols="30" value=""
              onchange="show()"></textarea>

    <script type="text/javascript">
        function show(){
            alert("您在文本框中添加了新的内容...")
        }
    </script>
</body>

Select: 当一个文本框,文本区域对象中的文本被选中时就会触发Select事件,未被选择则不会出现提示框.

<body>
    <input type="text" value="hello lyshark" onselect="show()">

    <script type="text/javascript">
        function show(){
            alert("您选中了文本框中的文本内容...")
        }
    </script>
</body>

Error: 当网页因为某种原因出现错误时就会触发,在错误处理程序中可以绑定操作,该标签常用与<body>,<img>配合.

<body>
    <img src="temp.jpg" onerror="error_msg()">

    <script type="text/javascript">
        function error_msg(){
            alert("图片加载失败了...")
        }
    </script>
</body>

JavaScript 对象编程

对象是编程语言中很重要的特征之一,JS是基于对象的编程语言,所以支持面向对象的所有特性,灵活使用这些对象能够实现丰富而强大的功能,下面我们首先来看如何创建一个自定义类,代码如下:

<body>
    <script type="text/javascript">
        function MyClass(name,age){                  //定义类,类名MyClass
            this.name = name;
            this.age = age;

            this.print = function(name,age){         //定义的一个函数体
                document.write("姓名: " + this.name + "年龄: " + this.age);
            }
        }

        var temp = new MyClass("lyshark",22);        //实例化一个对象
        temp.print()                                 //调用对象中的函数体
    </script>
</body>

上述代码执行后会打印出姓名和年龄,但是这种写法在实例化对象时,系统会为每个对象中均保存了一个相同的print()函数,从而浪费内存,使用原型写法可以解决该问题,改进代码如下:

<body>
    <script type="text/javascript">
        function MyClass(name,age){
            this.name = name;
            this.age = age;
        }
        MyClass.prototype = {
            print:function(){
                document.write("姓名: " + this.name + "年龄: " + this.age);
            }
        }

        var temp = new MyClass("lyshark",22);        //实例化一个对象
        temp.print()                                 //调用对象中的函数体
    </script>
</body>

◆其他事件◆

打开关闭窗口: 利用window.open()打开网页,window.close()关闭打开的网页.

msg.html

<body bgcolor="#bc8f8f">
    <table width="300" height="200" border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td valign="top"> 网页通知
                <p> 这是一个通知信息,您可以忽略掉</p>
            </td>
        </tr>
    </table>
</body>

index.html

<body>
    <input type="button" value="弹出通知" onclick="msg()">
    <input type="button" value="关闭通知" onclick="msg_close()">
    <script type="text/javascript">
        function msg(){
            open("msg.html","通知",height=50,width=30,top=20,left=10);
        }
        function msg_close() {
            close()
        }
    </script>
</body>

弹出提示框: 点击按钮自动弹出Window.alert()提示消息框.

<body>

    <input type="button" value="点击弹窗" onclick="msg()">
    <script type="text/javascript">
        function msg(){
            alert("这是一个提示框...")
        }
    </script>
</body>

弹出选择框: Window.confirm()弹出一条信息让用户确认,包括确认和取消按钮.

<body>
    <input type="button" value="弹窗口" onclick="msg()">
    <script type="text/javascript">
        function msg(){
            if(confirm("请输入你的选项..")){
                alert("感谢您的参与..")       //确认按钮执行语句
            }else{
                alert("取消语句..")           //取消按钮执行语句
            }
        }
    </script>
</body>

弹出输入框: window.prompt()用于弹出一个输入框,可以让用户输入一些信息.

<body>
    <script type="text/javascript">
        var passwd = prompt("请输入密码(密码是123): ","");
        while(passwd !="123"){
            passwd = prompt("密码错误,请重新输入: ");
        }
        if(passwd =="123"){alert("密码正确...")}
    </script>
</body>

设置单次定时器: 以下案例,实现当点击删除按钮时,屏幕提示删除成功,在5秒后自动的隐藏标签.

<body>
    <div id="status" style="color: red;"> </div>
    <input type="button" value="删除定时" onclick="DeleteStatus()">

    <script type="text/javascript">
        function DeleteStatus(){
            var temp = document.getElementById("status");
            temp.innerText = "删除成功了...";
            setTimeout(function(){
                temp.innerText = "";
            },50000);                     //设置5秒后执行清空标签
        }
    </script>
</body>

输入框触发事件: 当输入框中输入内容时,自动触发输入事件.

<form action="">
    手机号: <input type="text" id="userphone">
    <input type="submit">
</form>
    <script type="text/javascript">
    // 输入框发生变化触发
    document.getElementById("userphone").oninput=function(){
        console.log(this.value);
    }
    // 键盘按下触发
    document.getElementById("userphone").onkeyup=function(){
        console.log(this.value);
    }
</script>

网络相关事件: 当网络断开,或者连接时自动触发的事件.

<script>
    // 网络联通后执行
    window.addEventListener("online",function(){
        console.log("网络已连接");
    });
    // 网络断开后触发
    window.addEventListener("offline",function(){
        console.log("网络已断开");
    });
</script>

设置循环定时器: setIntercal设置定时器,clearInterval清除定时器,定时器用于周期性执行.

<body>
    <input type="text" id="clock">
    <input type="button" value="开始执行" onclick="begin_func()">
    <input type="button" value="取消执行" onclick="end_func()">

    <script type="text/javascript">
        function begin(){
            var now = new Date();
            var stime = now.getTime()
            var ret = document.getElementById("clock");
            ret.value=stime;
        }

        var ID;                                //定义全局变量,后期用于清楚定时器
        function begin_func(){
             ID =setInterval(begin,1000);     //每隔1秒执行一次,设置定时器
        }
        function end_func(){
            clearInterval(ID);                //取消一秒内执行,清除定时器
            ID = undefined;
        }
    </script>
</body>

定时器设置按钮: 通过定时器计时默认将按钮禁止点击,等超过五秒后将按钮变为可点击状态.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<input type="button" id="btnShow" disabled="true" value="等待5秒后可用"/>

<script type="text/javascript">
    var time1 = 5;
    var id1, btnShow;
    onload = function () 
    {
        // 获取按钮,启动定时器
        btnShow = document.getElementById('btnShow');
        id1 = setInterval('changeBtn(btnShow)', 1000);
    };

    function changeBtn(btn1) {
        time1--;
        btn1.value = "等待" + time1 + "秒后可用";
        if (time1 == 0) 
        {
            // 当5秒结束后让按钮可用
            btn1.value = "立即注册";
            btn1.disabled = false;
            clearInterval(id1); // 停止定时器
        }
    }
</script>

动态生成超链接: 通过循环的方式动态生成超链接,并设置点击后变为红色.

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

<script type="text/javascript">
    onload = function () {
        //获取容器
        var div = document.getElementById('myDiv');
        
        //循环创建5个超链接
        for (var i = 0; i < 5; i++) {
            //创建a对象
            var a = document.createElement('a');
            //为属性赋值
            a.href = 'http://www.itcast.cn';
            a.innerHTML = '链接' + i;
            a.onclick = function() {
                //设置背景色为红色
                this.style.backgroundColor = 'red';
                return false;
            };
            //追加到容器中
            div.appendChild(a);
        }
    };
</script>

绘制方框嵌套图: 每次循环并绘制方框图.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
    onload = function () {
        //根据标签获取body元素
        var body = document.getElementsByTagName('body')[0];
        //规定初始值
        var width = 500, height = 500, left = 10, top = 10;
        //循环创建div
        while (true) {
            //创建div加入body中
            var div1 = document.createElement('div');
            div1.style.position = 'absolute';
            div1.style.left = left + 'px';
            div1.style.top = top + 'px';
            div1.style.border = '1px solid blue';
            div1.style.width = width + 'px';
            div1.style.height = height + 'px';
            body.appendChild(div1);
            
            //改写数值
            left += 5;
            top += 5;
            width -= 10;
            height -= 10;
            
            //当div的宽度<=0时,在页面上不会显示,所以退出循环
            if (width <= 0) {
                break;
            }
        }
    };
</script>

DIV显示隐藏: 默认DIV为显示状态,当我们点击按钮后自动收缩隐藏.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<input type="button" id="btnShow" value="隐藏"/>
<div style="border: 1px solid red;" id="divShow">test</div>

<script type="text/javascript">
    onload = function() {
        document.getElementById('btnShow').onclick = function () {
            var divShow = document.getElementById('divShow');
            if (this.value == '隐藏') {
                this.value = '显示';
                divShow.style.display = 'none';//控制层隐藏
            } else {
                this.value = '隐藏';
                divShow.style.display = 'block';//控制层显示
            }
        };
    };
</script>

图片跟随鼠标移动: 让一张图片跟随屏幕鼠标动态调整.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<img id="img1" style="background: red;width: 20px; height: 20px;position: absolute;" />

<script type="text/javascript">
    onload = function() {
        //鼠标移动:mousemove
        window.onmousemove = function (e) {
            //获取图片对象
            var img1 = document.getElementById('img1');
            //设置x坐标
            img1.style.left = e.clientX - parseInt(img1.width) / 2 + 'px';
            //设置y坐标
            img1.style.top = e.clientY - parseInt(img1.height) / 2 + 'px';
        };
    };
</script>

显示按钮详细信息: 将鼠标放到按钮上,即可显示出按钮的详细信息.

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

<input type="button" id="btn1" value="一号"/>
<input type="button" id="btn2" value="二号"/>
<div style="width: 100px;height: 100px; position: absolute;display: none;" id="divShowId"></div>

<script type="text/javascript">
    onload = function () {
        //获取所有按钮
        var btns = document.getElementsByTagName('input');
        //遍历按钮,绑定事件
        for (var i = 0; i < btns.length; i++) {
            btns[i].onmouseover = function(e) {
                //获取div
                var divShowId = document.getElementById('divShowId');
                divShowId.textContent = this.value;
                //显示
                divShowId.style.display = 'block';
                //定义位置
                divShowId.style.left = e.clientX + 'px';
                divShowId.style.top = e.clientY + 'px';
            };
            btns[i].onmouseout = function() {
                //获取div
                var divShowId = document.getElementById('divShowId');
                //隐藏
                divShowId.style.display = 'none';
            };
        }
    };
</script>

按钮点击事件: 当用户点击按钮时,会自动将按钮的标题设置为其他值.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<input type="button" name="btnCry" id="0" value="哈哈"/>
<input type="button" name="btnCry" id="1" value="哈哈"/>
<input type="button" name="btnCry" id="2" value="哈哈"/>
<input type="button" name="btnCry" id="3" value="哈哈"/>
<input type="button" name="btnCry" id="4" value="哈哈"/>
    
<script type="text/javascript">
    //事件只能接收函数,这里直接使用匿名函数更简便
    onload = function () {
        //获取所有name为btnCry的按钮
        var btn = document.getElementsByName('btnCry');
        for (var i = 0; i < btn.length; i++) {
            //逐个为按钮注册点击事件
            btn[i].onclick = function () {
                //改写按钮的显示文本
                this.value = '呜呜';
            };
        }
    };
</script>

给图片添加描述: 当鼠标经过特定的图片时,就显示出图片的具体信息.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style>
        #showCountry {
            position: absolute;display: none;
            width: 200px;height: 100px;
            border: 1px solid red;
            background-color: blue;color: white;
        }
    </style>
    <script>
        var list = {
            'zg': ['中国', '北京', '牡丹', '世界第二大经济体'],
            'mg': ['美国', '华盛顿', '玫瑰', '白人与黑人一起劳动,却想到仇视'],
            'rb': ['日本', '东京', '樱花', '世界文明的两样东西:忍者和A片'],
            'hg': ['韩国', '首尔', '无穷', '民族意识超强']
        };

        onload = function () {
            //获取所有图片
            var imgs = document.getElementsByTagName('img');
            //为每个图片指定指向、移开事件
            for (var i = 0; i < imgs.length; i++) {
                imgs[i].onmouseover = function(e) {//指向国旗显示国家信息
                    //获取国家信息
                    var msg = list[this.id];
                    //构造描述字符串
                    var msgStr = '国家:' + msg[0] + '<br>首都:' + msg[1] + '<br>国花:' + msg[2] + '<br>描述:' + msg[3];
                    //获取div
                    var showCountry = document.getElementById('showCountry');
                    //显示div
                    showCountry.style.display = 'block';
                    //设置描述信息
                    showCountry.innerHTML = msgStr;
                    //让div在鼠标的位置显示
                    showCountry.style.left = e.clientX + 'px';
                    showCountry.style.top = e.clientY + 'px';
                };
                imgs[i].onmouseout = function() {//移开国旗隐藏显示
                    //获取div
                    var showCountry = document.getElementById('showCountry');
                    showCountry.style.display = 'none';
                };
            }
        };
    </script>
</head>
<body>
    <img id="zg"  width="100" height="100" />
    <img id="mg"  width="100" height="100" />
    <img id="rb"  width="100" height="100" />
    <img id="hg"  width="100" height="100" />
    <div id="showCountry"></div>
</body>

动态生成表格: 通过JS代码动态的生成表格,将鼠标放上后会高亮本行.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
    var bgColor;
    var list = [
        { id: '1', country: '中国', capital: '北京' },
        { id: '2', country: '美国', capital: '华盛顿' },
        { id: '3', country: '日本', capital: '东京' },
        { id: '4', country: '韩国', capital: '首尔' }
    ];
    onload = function() {
        var body = document.getElementsByTagName('body')[0];
        
        //创建表格
        var table = document.createElement('table');
        table.border = 1;
        body.appendChild(table);
        
        //创建标题行
        var thead = document.createElement('thead');
        var item0 = list[0];
        for (var key0 in item0) {
            //创建标题单元格
            var th = document.createElement('th');
            th.innerText = key0;
            thead.appendChild(th);
        }
        table.appendChild(thead);

        for (var i = 0; i < list.length; i++) {
            //遍历对象
            var item = list[i];
            //创建行
            var tr = document.createElement('tr');
            table.appendChild(tr);
            //注册事件
            tr.onmouseover = function () {//指向行时高亮
                //改变颜色前,先获取值,用于恢复
                bgColor = this.style.backgroundColor;
                this.style.backgroundColor = 'green';
            };
            tr.onmouseout = function() {//移开行时恢复原来颜色
                this.style.backgroundColor = bgColor;
            };
            //设置行的背景色
            if (i % 2 == 0) {
                tr.style.backgroundColor = 'red';
            } else {
                tr.style.backgroundColor = 'blue';
            }
            
            //遍历对象
            for (var key in item) {
                //创建单元格
                var td = document.createElement('td');
                td.innerText = item[key];
                tr.appendChild(td);
            }
        }
    };
</script>

◆反调试◆

禁用F12调试键

<script type="text/javascript">
window.onkeydown = window.onkeyup = window.onkeypress = function (event) {
    if (event.keyCode === 123) {
        event.preventDefault(); // 阻止默认事件行为
        window.event.returnValue = false;
    }
}
</script>

禁用页面的ctrl功能,来禁止ctrl+S保存功能

<script type="text/javascript">
//禁用页面的ctrl功能,来禁止ctrl+S保存功能
window.addEventListener('keydown', function (e) {
    if(e.keyCode == 83 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)){
        e.preventDefault();
    }
})
</script>

禁用页面的ctrl功能,来禁止ctrl+C保存功能

<script type="text/javascript">
window.addEventListener('keydown', function (e) {
    if(e.keyCode == 67 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)){
        e.preventDefault();
    }
})
</script>

屏蔽Ctrl+Shift+I

<script type="text/javascript">
window.addEventListener('keydown', function (e) {
    if((e.ctrlKey) && (e.shiftKey) && (e.keyCode == 73)){
        e.preventDefault();
    }
})
</script>

为右键添加自定义事件,禁用菜单右键,或者使用HTML插入代码来禁用菜单.

<script type="text/javascript">
window.oncontextmenu = function() {
    event.preventDefault();
    return false;
}
</script>

<body leftmargin=0 topmargin=0 oncontextmenu='return false' ondragstart='return false' 
onselectstart ='return false' onselect='document.selection.empty()' 
oncopy='document.selection.empty()' onbeforecopy='return false' onmouseup='document.selection.empty()'>

当通过特殊途径打开浏览器调试窗口时,会无限刷新,导致无法调试

<script type="text/javascript">
var x = document.createElement('div');
var isOpening = false;
Object.defineProperty(x, 'id', {
  get:function(){
     console.log("Please close debug now");
      window.location.reload()
  }
});
console.info(x);
</script>

当通过特殊途径打开F12时,会清空页面内容.

<script type="text/javascript">
var x = document.createElement('div');
var isOpening = false;
Object.defineProperty(x, 'id', {
  get:function(){
    bodys=document.body.firstChild.data;
    document.body.innerHTML=bodys;
    heads = document.head.firstChild.data;
    document.head.innerHTML=heads;
    document.open();
    document.close();
  }
});
console.info(x);
</script>

当控制台被打开时,自动清空所有内容,只保留一段话.

<script type="text/javascript">
document.onkeydown = document.onkeyup = document.onkeypress = function(event) { 
  var e = event || window.event || arguments.callee.caller.arguments[0]; 
  if (e && e.keyCode == 123) { 
	document.open();
	document.close();
	var docFragment = document.createDocumentFragment();
	var node = document.createElement("b");
	var node_text = document.createTextNode("请勿调试本页面..");
	node.appendChild(node_text);
	docFragment.appendChild(node);
	document.body.appendChild(docFragment);
	} 
}
</script>

自动触发点击指定标签

<script type="text/javascript">
setTimeout(function() {
    // IE
    if(document.all) {
        document.getElementById("clickMe").click();
    }
    // 其它浏览器
    else {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById("clickMe").dispatchEvent(e);
    }
}, 2000);
</script>
  
<a href="http://www.baidu.com" id="clickMe">触发onclick</a>

反调试之,禁止打开F12

window.onkeydown = window.onkeyup = window.onkeypress = function (event) {
        event.preventDefault();
        window.event.returnValue = false;
}
window.oncontextmenu = function() {
    event.preventDefault();
    return false;
}

var threshold = 160; 
window.setInterval(function() {  
    if (window.outerWidth - window.innerWidth > threshold || window.outerHeight - window.innerHeight > threshold){    
        window.location.href="https://www.baidu.com";
}
},100);