当前位置: 移动技术网 > IT编程>网页制作>CSS > JavaScript事件基础解析

JavaScript事件基础解析

2019年04月19日  | 移动技术网IT编程  | 我要评论

学习目标:

什么是事件 html事件 dom0级事件 常用的鼠标与键盘事件 this的指向

事件就是文档或窗口中发生的一些特定的交互瞬间。

html事件:直接在html元素标签内添加事件,执行脚本。

在html元素上绑定事件。

说明:执行脚本可以是一个函数的调用。

onload 页面加载时触发
onclick 鼠标点击时触发
onmouver 鼠标滑过时触发
onmouseout 鼠标离开时触发
onfocus 获得焦点时触发
onblur 失去焦点时触发
onchange 域的内容改变时发生

关于this指向:

在事件触发的函数中,this是对该dom对象的引用。

.btn{
            width: 140px; height: 30px; line-height: 30px; background:#00f;color: #fff;
            font-size: 14px;text-align: center;border-radius:5px ;cursor: pointer; margin-top: 30px;
        }

开始

<script> function mouseoverfn(btn){ btn.style.background="#f00"; } function mouseoutfn(btn){ btn.style.background="#00f"; } </script>
.btn{
            width: 140px; height: 30px; line-height: 30px; background:#00f;color: #fff;
            font-size: 14px;text-align: center;border-radius:5px ;cursor: pointer; margin-top: 30px;
        }

开始

<script> function mouseoverfn(btn,bgcolor){ btn.style.background=bgcolor; } function mouseoutfn(btn,bgcolor){ btn.style.background=bgcolor; }

dom0级事件:事件的绑定

通过dom获取html元素 (获取html元素).事件=执行脚本

ele.事件=执行脚本 在dom对象上绑定事件。执行脚本可以是一个匿名函数,也可以是一个函数的调用。


//获取按钮
    var btn=document.getelementbyid("btn");
    //给每个按钮绑定事件
    /*function abc();
    btn.onclick=abc;*/
    //给按钮绑定事件,this是对该dom元素的引用。
    btn.onclick=function(){
        //1
        /*console.log(this)//

锁定

*/ //2 /*this.classname="unlock" this.innerhtml="解锁";*/ //判断如果按钮是锁定则显示为解锁内容为灰色。否则显示为锁定,变为蓝色。 //通过classname判断 if(this.classname=="lock"){ this.classname="unlock"; this.innerhtml="解锁" }else{ this.classname="lock"; this.innerhtml="锁定"; } //innerhtml判断 if(this.innerhtml=="锁定"){ this.classname="unlock"; this.innerhtml="解锁" }else{ this.classname="lock"; this.innerhtml="锁定"; }

不建议使用html事件原因:

多元素绑定相同事件时,效率低。 不建议在html中写js代码。

  var btn=document.getelementbyid("btn");
    function clickbtn(){
        alert("我是按钮");
    }

    btn.onclick=clickbtn;//一定没有括号

</script>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网