JavaScript事件

发布时间 2023-11-18 10:00:28作者: L_GuoZY

一、  JavaScript事件

在前端中,页面的每次交互和特效都是一个事件,其中任何一个html元素都是一个事件源,一个很事件源可以添加多个事件。

二、 事件中的event对象  

只要发生一个事件就会产生一个event事件,event代表事件的状态

1、event事件常见的属性和状态

2、阻止默认事件的发生

对于一些标签来说,他们拥有自己的事件,比如:a标签可以跳转,submit/button可以提交表单,reset可以重置按钮,那么如果想要给这些按钮添加事件,并且不让他执行对应的默认事件的话,就需要使用自制时间发生; 阻止默认事件的方法有两种:使用的是事件对象的方法来阻止event.stopPropagation();或者 return fales;

3、事件流-冒泡机制

事件的流向,是由两个机制,一个是事件的捕获 元素由外向内,另一个是元素的冒泡由内向外

注意:如果存在浏览器的兼容性问题可能会导致不同浏览器 出现冒泡程度不同

4、阻止冒泡的方法

 event.stopPropagation()

兼容性写法:

if(event && event.stopPropagation){  // w3c标准 
  event.stopPropagation(); 
}else{  // IE系列 IE 678 
  event.cancelBubble = true; 
}

“DOM事件流”:三个阶段:事件捕获,成为目标阶段,事件冒泡

三、 js触发事件的方式有哪些

1、在js获取元素/标签      元素.事件名称 = 匿名函数 / function(){}

2、元素.事件名称 = 函数名称

3、 在html中触发    onclick = "代码段 / 函数调用"

四、鼠标事件

五、键盘事件

想要区分键盘上的每个按键,是通过键盘的keyCode值来判断的,所以想要知道按下的是哪个按键,可以使用event.keyCode

document.onkeyup = function(){
    console.log(event.keyCode);
}

案例:控制小人移动

<style>
        .box {
            width: 30px;
            height: 30px;
            /* border: 1px solid red; */
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="box">
        <img src="./img/ren_q_1.gif" alt="">
        <!-- <img src="./img/ren_q_2.gif" alt="">  -->
    </div>
var box = document.querySelector('.box')
        var img = document.querySelector('.box img');
        var flag = true;
        var left = 0;
        var tops = 0;
        var timer = null;

        function dong(walk) {
            flag = !flag;
            var imgname = flag ? `ren_${walk}_1.gif` : `ren_${walk}_2.gif`
            img.src = './img/' + imgname;
        }
        timer=setInterval(function () {
            dong('q');
        }, 200);
        clearInterval(timer)
        document.onkeydown = function () {
            switch (event.keyCode) {
                case 65:
                    left -= 10;
                    dong('l')
                    break;
                case 87:
                    tops -= 10;
                    dong('h')
                    break;
                case 68:
                    left += 10;
                    dong('r')
                    break;
                case 83:
                    tops += 10;
                    dong('q')
                    break;
            }
            box.style.left = `${left}px`;
            box.style.top = `${tops}px`;
        }

六、光标事件

案例: 小米官网搜索框

*{
            margin: 0;
            padding: 0;
                }
         input{
            width: 300px;
            height: 50px;
            outline: 0;
            border: 1px solid rgb(118, 118, 118);
            margin-left:100px ;
        }
        ul{
            width: 300px;
            height: 0px;
            border: 0px solid #ff6700;
            margin-left: 100px;
            overflow: hidden;
            
        }
        li{
            list-style: none;
            line-height: 50px;
            margin-left: 20px;
            color: #666;
        }
    </style>
</head>
<body>
    <input type="text" name="" id="inp">
    <ul id="ul">
        <li>小米家电</li>
        <li>小米手机</li>
        <li>红米手机</li>
        <li>小米电脑</li>
        <li>小米平板</li>
        <li>小米手表</li>
    </ul>
</body>
 var height = 0;
    var timer = null;
    inp.onfocus= function(){
        inp.style.border = '1px solid #ff6700';
        timer = setInterval(function(){
            if(height >=300){
                clearInterval(timer)
            }else{
                height+=10  
            ul.style.height = height+'px';
            ul.style.border = '1px solid #ff6700';
            }
            
        },20)
        

    }
    inp.onblur = function(){
        inp.style.border = '1px solid rgb(118, 118, 118)'; 
        ul.style.display = 'none'

    }

 七、窗口事件

八、表单事件

案例: 苏宁登录页面

当输入input框内时会出现×,点击取消内容,密码框出现小眼睛,点击睁开会实现密码框显示

<style>
        input{
            width: 300px;
            height: 50px;
            outline: 0;
            border: 0;
            border-bottom:1px solid #ccc  ;
            line-height: 50px;
            margin-left: 500px;
        }
        #inp1{
            margin-top: 100px;
        }
        span{
            display: none;
            cursor: pointer;
        }
        .imgs{
            position: absolute;
            margin-right: 100px;
            /* border: 1px solid red; */
            top: 180px;
            left: 750px;
            display: none;
        }
    </style>
</head>
<body>
    <input type="text" name="" id="inp1" placeholder="请输入手机号/用户名/邮箱"><span id="eorr">X</span><br>
    <input type="password" name="" id="inp2" placeholder="请输入密码"><img class="imgs" src="./xiaomi.img/yanjing_yincang_o.png" alt=""></span><span id="eorr2" >X</span>
 <script>
        var imgs = document.querySelector('.imgs')
       var flag  = true;

       //点击事件取消input的值
        eorr.onclick = function(){
            inp1.value = '';
        }
        eorr2.onclick = function(){
            inp2.value = '';
        }
        //input表单触发生成对应按键
        inp1.oninput = function(){
            if( inp1.value.length>0){
                eorr.style.display = 'inline-block';
            }else{
                eorr.style.display = 'none';
            }
        }
        inp2.oninput = function(){
            if( inp2.value.length>0){
                eorr2.style.display = 'inline-block';
                imgs.style.display = 'inline-block';
            }else{
                eorr2.style.display = 'none';
            }
        }
        //点击切换输入密码框
        imgs.addEventListener('click',function(){
           if(flag){
            imgs.src = `./xiaomi.img/yanjing.png`
            inp2.type = 'text'
            flag = !flag
           }else{
            imgs.src = `./xiaomi.img/yanjing_yincang_o.png`
            inp2.type = 'password'
            flag = !flag
           }
        })
    </script>

九、单选框和复选框被选中

案例:简易购物车案例

<table border='1' width="500">
        <tr>
            <td>选择</td>
            <td>商品名称</td>
            <td>商品数量</td>
            <td>商品价格</td>
            <td>总价</td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" class="sel"/>
            </td>
            <td>上衣</td>
            <td>
                <button  class="jian">-</button>
                <span class="num">5</span>
                <button class="add">+</button>
            </td>
            <td class="price">100</td>
            <td class="prices"></td>
        </tr>
        <tr>
            <td><input type="checkbox" class="sel"/></td>
            <td>裤子</td>
            <td>
                <button  class="jian">-</button>
                <span class="num">2</span>
                <button class="add">+</button>
            </td>
            <td class="price">200</td>
            <td class="prices"></td>
        </tr>
        <tr>
            <td><input type="checkbox" class="sel"/></td>
            <td>包包</td>
            <td>
                <button class="jian">-</button>
                <span class="num">1</span>
                <button class="add">+</button>
            </td>
            <td class="price">300</td>
            <td class="prices"></td>
        </tr>
        <tr>
            <td>全选:<input type="checkbox" id="checkAll"/></td>
            <td colspan="4" id='totlePrice'>总价:0</td>
        </tr>
    </table>
 // 1. 获取所有的复选框
    var sel = document.querySelectorAll('.sel');
    var prices = document.querySelectorAll('.price');
    var onePrices = document.querySelectorAll('.prices');
    var nums = document.querySelectorAll('.num');
    var adds = document.querySelectorAll('.add');
    var jians = document.querySelectorAll('.jian');

    // 2. 给复选他添加事件
    for(var i=0;i<sel.length;i++){
        (function(i){
            sel[i].onclick = function(){
                allTotle();
                // console.log(sum);
            }
        })(i)
    }

    // 5. 计算商品总价
    function allTotle(){
        let sum = 0;
        // 3. 判断是否被选中
        for(let j=0;j<sel.length;j++){
            if(sel[j].checked){
                sum += parseFloat(onePrices[j].innerHTML)  
            }
        }
        totlePrice.innerHTML = `总价:${sum}`;
    }

    // 3. 单个商品的总价
    function totle(){
        for(var i=0;i<prices.length;i++){
            onePrices[i].innerHTML = prices[i].innerHTML*nums[i].innerHTML;
        }
    }

    // 4. 点击添加数量
    for(var i=0;i<adds.length;i++){
        adds[i].index = i;
        adds[i].onclick = function(){
            // this值得是被触发事件的元素本身
            nums[this.index].innerHTML = parseInt(nums[this.index].innerHTML) + 1;
            // 单个商品的总价重新计算
            totle();
            // 计算商品总价
            allTotle();
        }
    }
     // 4. 点击减少数量
     for(var i=0;i<jians.length;i++){
        jians[i].index = i;
        jians[i].onclick = function(){
            // this值得是被触发事件的元素本身
            nums[this.index].innerHTML = parseInt(nums[this.index].innerHTML) - 1;
            // 单个商品的总价重新计算
            totle();
            // 计算商品总价
            allTotle();
        }
    }

    // 页面加载进来之后调用
    totle();

    // 6. 全选
    checkAll.onclick = function(){
        console.log(checkAll.checked);
        for(let j=0;j<sel.length;j++){
            sel[j].checked = checkAll.checked;
        }
        // 计算总价
        allTotle()
    }

十、加载事件

正常情况下,js代码是可以写在head标签中,也可以写在/body结束的后面;但是当我们把js代码写在head中,并且js代码中有获取页面html标签的操作的时候,这时候的js代码就会报错  

页面加载完成 ,  script就可以写到页面内容的前面

十一、滚动事件

案例:楼层导航

 <style>
        * {
          margin: 0;
          padding: 0;
        }
        ul,li {
          list-style: none;
        }
        .header {
          position: fixed;
          left: 0;
          top: 0;
          height: 40px;
          width: 100%;
          background-color: rgb(238, 215, 110);
          line-height: 40px;
        }
        .header ul {
          display: flex;
          justify-content: space-around;
        }
        .header ul li.active {
          color: #f00;
        }
        .empty {
          height: 40px;
        }
        .product {
          background-color: rgb(178, 204, 238);
          height: 500px;
        }
        .ratings {
          background-color: rgb(178, 238, 218);
          height: 200px;
        }
        .detail {
          background-color: rgb(231, 238, 190);
          height: 900px;
        }
        .recommend {
          background-color: rgb(241, 202, 220);
          height: 800px;
        }
      </style>
<div class="header">
        <ul>
          <li class="active">商品</li>
          <li>评价</li>
          <li>详情</li>
          <li>推荐</li>
        </ul>
      </div>
      <div class="empty"></div>
      <div class="product floor">
        商品
      </div>
      <div class="ratings floor">
        评价
      </div>
      <div class="detail floor">
        详情
      </div>
      <div class="recommend floor">
        推荐
      </div>
var floorAll = document.querySelectorAll('.floor');
    var liAll = document.querySelectorAll('.header li');
    // var timer;
    for (let i = 0; i < liAll.length; i++) {
            liAll[i].onclick = function () {
                // 移除所有li的颜色
                for (let j = 0; j < liAll.length; j++) {
                    liAll[j].style.color = '#000'; // 设置默认颜色
                }
                // 设置当前点击的li元素颜色
                liAll[i].style.color = 'blue';
                // 滚动到指定位置
                window.scrollTo({
                    top: floorAll[i].offsetTop - 40,
                    behavior: 'smooth'
                });
            };
        }

 文档页面高度

案例:鼠标缩放盒子

<style type="text/css"> 
            /* *{ 
            margin: 0; 
            }  */
        .wrap{ 
        width: 100px; 
        height: 100px; 
        background-color: #ccc; 
        position: relative; 
        } 
        .btn{ 
        position: absolute; 
        bottom: 0; 
        right: 0; 
        width: 20px; 
        height: 20px; 
        background-color: red; 
        } 
        </style> 
</head>
<body>
    <div class="wrap"> 
        <div class="btn"></div> 
    </div>
var warp = document.querySelector('.wrap');
        var btn = document.querySelector('.btn');
        btn.onmousedown = function(e){
            var e = e || window.event;
                //获取btn 的当前位置
                var mouseX = e.clientX;
                var mouseY = e.clientY;
                 console.log(mouseX,mouseY);
                 // 获取初始大小
                 var Width = warp.offsetWidth;
                 var Height = warp.offsetHeight;
            document.onmousemove = function(e){
               // 获取移动后的位置
               var e = e || window.event;
                var nowX = e.clientX;
                var nowY = e.clientY;
                console.log(nowX,nowY);
                // 去差值
                var chaX = nowX - mouseX;
                var chaY = nowY - mouseY;   
                warp.style.width = Width + chaX + 'px';
                warp.style.height = Height + chaY + 'px';
            }
        }
        document.onmouseup = function(){
            document.onmousemove = false;
        }

十二、js 两种添加事件的方式

1、on +  事件名

2、添加点击事件

十三、DOM css动态样式

十四、event对象使用技巧