12.31

285 阅读1分钟

1:键盘事件:

  • onkeyup:某个键盘按键被松开是触发

  • onkeydown:某个键盘按键被按下时触发(识别所有)

  • onkeypress:某个键盘按键被按下时触发(不识别功能键。shift,ctrl等等)顺序是:先down-press-up

      <script>   
    //按下字符键时,依次打印:keydown keypress keyup
    document.onkeydown = function(e){
    console.log("keydown");
    }
    document.onkeypress = function(e){
    console.log("keypress");
     }
     document.onkeyup = function(e){
      console.log("keyup");
    复制代码
    

    }

键盘事件对象属性:keyCode

可以按照来判断我们按下了哪个键👆、 鼠标事件:keyCode 测出键盘每个键 keyCode的值:

image.png

image.png

案列 两种方式打印:

                   alert(this.value)
                  alert(eObj.target.value) 
                 alert(eObj.target.innerHTML) 
复制代码

事件源的用途:

阻止冒泡的两种方式。打印表单内容: e.target.value 打印文档 e.target.innerHTML
获取鼠标点击的位置:e.clientX e.clientY
取消默认行为事件:e.preventDefault()

     用户名:<input type="text" name="" id="text">

    var text = document.getElementById('text')
    text.addEventListener('keydown',function(e){
      console.log(e);
        let eObj = e||event
        console.log(eObj.keyCode);
        if(eObj.keyCode==13){
            // alert(this.value)
            alert(eObj.target.value)
        }
     })
复制代码

2:鼠标点击的位置

image.png

3:默认行为:

image.png

阻止默认行为:return false; e.preventDefault()

             <script>
            window.onload = function()
             {
             var oForm = document.getElementById('form1');

                  oForm.onsubmit = function(e)
                   {
                 return false; //阻止表单提交,组织默认样式
                 e.preventDefault()
                    }
                 }
             </script>
              <body>
          <form id="form1" action="http://www.baidu.com"> 
         <input type="submit"></form> 
          </body>
          
复制代码

鼠标点击右键的时候会发生的事件: document.oncontextmenu=fuction ()

此处也有阻止默认跳转:return false; e.preventDefault() 两个有区别:return false 后面的打印1 不会执行了,e.preventDefault()阻止跳转行为,后面执行区块会继续执行

         document.oncontextmenu=fuction (){
         alert()
         console.log(1)
         return false;
         e.preventDefault()
     
         }
         

          
          
复制代码

4:拖拽事件

image.png 盒子的位置(lefttop值)= 鼠标的位置(lefttop值)- 鼠标按下时与盒子之间的距离(lefttop值)。

处理鼠标按下事件

image.png

处理鼠标移动事件

image.png

处理释放鼠标按键的事件

用户松开鼠标按键后,依然可以进行拖拽。
故实现鼠标按钮松开后,弹框不再移动。

image.png

处理关闭弹框事件

image.png

5:用户界面事件

window.onload=函数表达式

是业内中所有元素加载完成后,浏览器自动触发该事件 注册事件放在head里面

window.onresize=函数表达式

事件会在窗口被调整大小时候发生

案列:

     window.onload=function(){
        let  a = document.getElementById('a')
     a.onclick=function(){
          alert(a.target.innerHTML)
           
        }
        window.onresize=function(){
            alert('页面尺寸改变')
            a.style.backgroundColor='red'
            
        } */
        // 当页面尺寸发生变化的时候 dom文档已经加载完毕
   
        window.onresize=function(){
            alert(a.target.innerHTML)
   }


作者:用户8712537862007
链接:juejin.cn/post/704779… 来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。