DOM Event(事件)

一、DOM Event(事件)

1、事件类型

onclick        当用户点击某个对象时调用的事件句柄。
ondblclick     当用户双击某个对象时调用的事件句柄。

onfocus        元素获得焦点。               练习:输入框
onblur         元素失去焦点。               应用场景:用于表单验证,用户离开某个输入框时,代表已经输入完了,我们可以对它进行验证.
onchange       域的内容被改变。             应用场景:通常用于表单元素,当元素内容被改变时触发.(三级联动)

onkeydown      某个键盘按键被按下。          应用场景: 当用户在最后一个输入框按下回车按键时,表单提交.
onkeypress     某个键盘按键被按下并松开。
onkeyup        某个键盘按键被松开。

onload         一张页面或一幅图像完成加载。

onmousedown    鼠标按钮被按下。
onmousemove    鼠标被移动。
onmouseout     鼠标从某元素移开。
onmouseover    鼠标移到某元素之上。
onmouseleave   鼠标从元素离开

onselect       文本被选中。
onsubmit       确认按钮被点击。

2、绑定事件方式

方式1:

<div id="div" onclick="foo(this)">点我呀</div>

<script>
    function foo(self){           // 形参不能是this;
        console.log("点你大爷!");
        console.log(self);   
    }
</script>

 方式2:

<p id="abc">试一试!</p>

<script>

    var ele=document.getElementById("abc");

    ele.onclick=function(){
        console.log("ok");
        console.log(this);    // this直接用
    };

</script>

3、事件类型

1、onload:

onload 属性开发中只给 body元素加。这个属性的触发标志着页面内容被加载完成。应用场景:当有些事情我们希望页面加载完立刻执行,那么可以使用该事件属性。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script>
         /*
              window.onload=function(){
                   var ele=document.getElementById("ppp");
                   ele.onclick=function(){
                   alert(123)
                };
             };
         
         */



          function fun() {
              var ele=document.getElementById("ppp");
               ele.onclick=function(){
                alert(123)
            };
          }

    </script>
</head>
<body onload="fun()">

<p id="ppp">hello p</p>

</body>
</html>
View Code

2、onsubmit:

当表单在提交时触发。该属性也只能给form元素使用。应用场景:在表单提交前验证用户输入是否正确。如果验证失败,在该方法中我们应该阻止表单的提交。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script>

        window.onload=function(){
            //阻止表单提交方式1().
            //onsubmit 命名的事件函数,可以接受返回值. 其中返回false表示拦截表单提交.其他为放行.

             var ele=document.getElementById("form");
             ele.onsubmit=function(event) {
            //    alert("验证失败 表单不会提交!");
            //    return false;

            // 阻止表单提交方式2 event.preventDefault(); ==>通知浏览器不要执行与事件关联的默认动作。
             alert("验证失败 表单不会提交!");
             event.preventDefault();

    }

        };

    </script>
</head>
<body>

<form id="form">
            <input type="text"/>
            <input type="submit" value="点我!" />
</form>

</body>
</html>
View Code

3、事件传播

<div id="abc_1" style="border:1px solid red;width:300px;height:300px;">
        <div id="abc_2" style="border:1px solid red;width:200px;height:200px;">

        </div>
</div>

<script type="text/javascript">
        document.getElementById("abc_1").onclick=function(){
            alert('111');
        };
        document.getElementById("abc_2").onclick=function(event){
            alert('222');
            event.stopPropagation(); //阻止事件向外层div传播.
        }
</script>
View Code

4、onselect:

<input type="text">

<script>
    var ele=document.getElementsByTagName("input")[0];

    ele.onselect=function(){
          alert(123);
    }

</script>
View Code

5、onchange:

<select name="" id="">
    <option value="">111</option>
    <option value="">222</option>
    <option value="">333</option>
</select>

<script>
    var ele=document.getElementsByTagName("select")[0];

    ele.onchange=function(){
          alert(123);
    }

</script>
View Code

6、onkeydown:

Event 对象:Event 对象代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态。
事件通常与函数结合使用,函数不会在事件发生前被执行!event对象在事件发生时系统已经创建好了,并且会在事件函数被调用时传给事件函数.我们获得仅仅需要接收一下即可.比如onkeydown,我们想知道哪个键被按下了,需要问下event对象的属性,这里就是KeyCode。

<input type="text" id="t1"/>

<script type="text/javascript">

    var ele=document.getElementById("t1");

    ele.onkeydown=function(e){

        e=e||window.event;

        var keynum=e.keyCode;
        var keychar=String.fromCharCode(keynum);

        alert(keynum+'----->'+keychar);

    };

</script>
View Code

7、onmouseout与onmouseleave事件的区别:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #container{
            width: 300px;
        }
        #title{
            cursor: pointer;
            background: #ccc;
        }
       #list{
           display: none;
           background:#fff;
       }

        #list div{
            line-height: 50px;
        }
        #list  .item1{
            background-color: green;
        }

         #list  .item2{
            background-color: rebeccapurple;
        }

         #list  .item3{
            background-color: lemonchiffon;
        }


    </style>
</head>
<body>


<p>先看下使用mouseout的效果:</p>

<div id="container">
        <div id="title">使用了mouseout事件↓</div>
        <div id="list">
                <div class="item1">第一行</div>
                <div class="item2">第二行</div>
                <div class="item3">第三行</div>
        </div>
</div>


<script>

// 1.不论鼠标指针离开被选元素还是任何子元素,都会触发 mouseout 事件。

// 2.只有在鼠标指针离开被选元素时,才会触发 mouseleave 事件。

   var container=document.getElementById("container");
   var title=document.getElementById("title");
   var list=document.getElementById("list");


   title.onmouseover=function(){
       list.style.display="block";
   };

   container.onmouseleave=function(){  // 改为mouseout试一下
       list.style.display="none";
   };

/*

因为mouseout事件是会冒泡的,也就是onmouseout事件可能被同时绑定到了container的子元素title和list
上,所以鼠标移出每个子元素时也都会触发我们的list.style.display="none";

*/


  /*
  思考:
  if:

       list.onmouseout=function(){
           list.style.display="none";
   };


     为什么移出第一行时,整个list会被隐藏?

     其实是同样的道理,onmouseout事件被同时绑定到list和它的三个子元素item上,所以离开任何一个
     子元素同样会触发list.style.display="none";

   */

</script>
</body>
</html>
View Code

二、课后作业

1、注册提示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .head {
            height: 40px;
            background: #1e2598;
        }

        .left {
            float: left;
            width: 15%;
            height: 600px;
            border-right: 1px black solid;

        }

        .right {
            float: left;
            width: 84%;
        }

        .add {
            margin: 10px 20px;
            width: 47px;
            height: 30px;
            color: white;
            background: royalblue;
            border-right: solid 1px black;
            border-bottom: solid 1px black;
            border-radius: 12%;
        }

        th, td {
            margin: 0 auto;
            text-align: center;
            border-bottom: 1px darkgray solid;

        }

        table tr {
            height: 40px;

        }

        tr {
            margin: 20px 0;
            padding: 20px;
            border-bottom: 1px darkgray solid;
        }

        .name {
            width: 6%;
        }

        .age {
            width: 6%;
        }

        .phone {
            width: 10%;
        }

        .city {
            width: 10%;
        }

        .control {
            width: 25%;
        }

        .bg {
            position: fixed;
            width: 100%;
            height: 100%;
            background: darkgray;
            opacity: 0.5;
        }

        .add_text {
            background: white;
            position: fixed;
            left: 50%;
            top: 50%;
            margin-top: -150px;
            margin-left: -150px;
            width: 350px;
            height: 300px;
        }

        .add_text input {

            width: 200px;
            height: 20px;
            font-size: 14px;
            margin: 10px;
        }

        .add_text p {
            float: right;
            margin-right: 35px;
            margin-top: 15px;
        }

        .add_text button {
            width: 50px;
            height: 20px;
            margin: 5px;
        }

        .hide {
            display: none;
        }

    </style>
</head>
<body>
<div class="bg hide handels"></div>
<div class="add_text hide handels">
    <p>姓名:<input name="user" placeholder="姓名"></p>
    <p>年龄:<input name="age" placeholder=""></p>
    <p>手机号:<input name="phone_number" placeholder=""></p>
    <p>城市:<input name="home_city" placeholder=""></p>
    <p id="butt">
        <button class="confirm">确定</button>
        <button class="cancel">取消</button>
    </p>
</div>
<div class="head"></div>
<div class="middle">
    <div class="left"></div>
    <div class="right">
        <button class="add">添加</button>
        <table>
            <tr class="title">
                <th class="name">姓名</th>
                <th class="age">年龄</th>
                <th class="phone">手机号</th>
                <th class="city">城市</th>
                <th class="control">操作</th>
            </tr>
            <tr class="row hide">
                <td class="name">egon</td>
                <td class="age">34</td>
                <td class="phone">12345678901</td>
                <td class="city">北京</td>
                <td class="control">
                    <button>编辑</button>
                    <button onclick="dell(this)">删除</button>
                </td>
            </tr>
            <tr>
                <td class="name">egon</td>
                <td class="age">34</td>
                <td class="phone">12345678901</td>
                <td class="city">北京</td>
                <td class="control">
                    <button>编辑</button>
                    <button onclick="dell(this)">删除</button>
                </td>
            </tr>
        </table>

    </div>
</div>

<script>
    function dell(self) {

        self.parentNode.parentNode.parentNode.removeChild(self.parentNode.parentNode)

    }

    var add = document.getElementsByClassName("add")[0];
    var hides = document.getElementsByClassName("handels");

    add.onclick = function () {

        for (var i = 0; i < hides.length; i++) {
            hides[i].classList.remove("hide");
        }

        var input = document.getElementsByTagName("input");
        for (i = 0; i < input.length; i++) {
            input[i].value = "";
        }
    };

    var confirm = document.getElementsByClassName("confirm")[0];
    confirm.onclick = function () {
        message = [];
        var input = document.getElementsByTagName("input");
        for (var i = 0; i < input.length; i++) {
            message.push(input[i].value)
        }
        console.log(message);
        for (i = 0; i < hides.length; i++) {
            hides[i].classList.add("hide");
        }
        var row = document.getElementsByClassName("row")[0];
        var new_row = row.cloneNode(true);
        new_row.classList.remove("hide")

        for (var j = 1; j < new_row.childNodes.length - 2; j += 2) {
            console.log(new_row.childNodes[j].innerText)
            new_row.childNodes[j].innerText = message[(j + 1) / 2 - 1]
        }
        var flag;
        for (var me in message) {
            if (message[me].length == 0) {
                flag = 0;
                break;
            }
        }
        if (flag == undefined) {
            row.parentNode.appendChild(new_row);
        }
    };

    var cancel = document.getElementsByClassName("cancel")[0];
    cancel.onclick = function () {
        for (var i = 0; i < hides.length; i++) {
            hides[i].classList.add("hide");
        }
    }

    var error = document.createElement("p");
    error.innerText = "2-10个字符,可使用字母、汉字、数字、不能是纯数字"
    error.style.color = "red"
    error.style.fontSize = "12px"
    error.style.lineHeight = "12px"
    error.style.float = "none"
    error.style.margin = "0"
    error.style.textAlign = "center"
    var error1 = error.cloneNode(true);
    error1.innerText = "请输入正确年龄"
    var error2 = error.cloneNode(true);
    error2.innerText = "请输入正确的手机号码"


    var user = document.getElementsByName("user")[0];
    user.onblur = function () {

        if (!isNaN(user.value) || user.value.length > 10 || user.value.length < 2) {
//            error = document.createElement("p");
//            error.innerText = "2-10个字符,可使用字母、汉字、数字、不能是纯数字"
//            error.style.color = "red"
//            error.style.fontSize = "12px"
//            error.style.lineHeight = "12px"
//            error.style.float = "none"
//            error.style.margin = "0"
//            error.style.textAlign = "center"

            if (!this.nextElementSibling) {
                this.parentNode.appendChild(error)
            }
        }
        else {
            if (this.nextElementSibling) {
                this.parentNode.removeChild(this.nextElementSibling)
            }
        }

    }

    var age = document.getElementsByName("age")[0];
    age.onblur = function () {

        if (isNaN(age.value) || age.value < 0 || age.value > 150 || age.value.length == 0) {
//            var error1 = document.createElement("p");
//            error1.innerText = "请输入正确年龄"
//            error1.style.color = "red"
//            error1.style.fontSize = "12px"
//            error1.style.lineHeight = "12px"
//            error1.style.float = "none"
//            error1.style.margin = "0"
//            error1.style.textAlign = "center"

            if (!this.nextElementSibling) {
                this.parentNode.appendChild(error1)
            }
        }
        else {
            if (this.nextElementSibling) {
                this.parentNode.removeChild(this.nextElementSibling)
            }
        }
    }

    var phone = document.getElementsByName("phone_number")[0];
    phone.onblur = function () {

        if (isNaN(phone.value) || phone.value.length != 11) {
//            var error2 = document.createElement("p");
//            error2.innerText = "请输入正确的手机号码"
//            error2.style.color = "red"
//            error2.style.fontSize = "12px"
//            error2.style.lineHeight = "12px"
//            error2.style.float = "none"
//            error2.style.margin = "0"
//            error2.style.textAlign = "center"
            if (!this.nextElementSibling) {
                this.parentNode.appendChild(error2)
            }
        }
        else {
            if (this.nextElementSibling) {
                this.parentNode.removeChild(this.nextElementSibling)
            }
        }
    }
</script>
</body>
</html>
参考答案

2、省、市二级联动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
<select name="province">
    <option value="">请选择省份:</option>
</select>
<select name="city">
    <option value="">请选择城市:</option>
</select>
<script>
    var data = {
        "河北省": ["石家庄", "保定", "邯郸"],
        "河南省": ["郑州", "洛阳", "平顶山"],
    }

    var province = document.getElementsByName("province")[0];
    var city = document.getElementsByName("city")[0];
    for (i in data) {
        var p = document.createElement("option");
        p.innerText = i;
        province.appendChild(p)
    }

    province.onchange = function () {

        pro = (this.options[this.selectedIndex]).innerText;
        console.log(city.options.length)
        if (city.options.length > 1) {
            for (var j = city.options.length; j > 1; j--) {
                city.removeChild(city.options[j - 1])
            }
        }


        for (var i = 0; i < data[pro].length; i++) {
            var c = document.createElement("option");
            c.innerText = data[pro][i];
            city.appendChild(c)
        }
    }
</script>
</body>
</html>
参考答案

 

posted @ 2017-08-10 15:44  maple-shaw  阅读(567)  评论(0)    收藏  举报