JavaScript事件

90 阅读1分钟

键盘事件

    // /* 键盘按下的时候触发 */
    // t.onkeydown=function(){
    //     console.log('我按下了键盘');
    // }
    // /* 键盘抬起的时候触发 */
    // t.onkeyup=function(){
    //     console.log('键盘我抬起了');
    // }
    // /* 连续敲击的时候触发,敲击并抬起触发 */
    // t.onkeypress=function(){
    //     console.log('连续触发');
    // }

    /* 顺序onkeydown > onkeypress > onkeyup */
    
    

右击默认行为

 <body>
        <!-- a标签的跳转是默认行为 -->
        <a href="http://www.baidu.com">百度</a>
        <form action="">
            <input type="submit" value="提交">
        </form>
        <script>
            /* 当鼠标右击时会发生的事件 */
            document.oncontextmenu=function(){
                /* 阻止了默认右击事件 */
                return false
            }

            let input=document.querySelector('input')
            input.onclick=function(e){
                console.log(1);
                e.preventDefault();
            }



            let a=document.querySelector('a')
            a.onclick=function(e){   
                this.style.backgroundColor='red'
                /* 取消默认事件 两种方法 */
                /* return false */
                /*事件源对象里面的取消默认事件的方法*/
                e.preventDefault();
            }
        </script>
</body>
    
    

拖拽组件

     <body>
        <div id="div1"></div>
        <script>
            let div1=document.getElementById('div1')
            div1.onmousedown=function(e){
                /* 按下的时候获取点的位置到盒子边缘的距离 */
                let arr=e.clientX -div1.offsetLeft
                let arr2=e.clientY -div1.offsetTop
                document.onmousemove =function(e){
                    /* 移动时候获取client的动态距离-到- 盒子内点到边缘的固定距离 */
                    /* 最后获得盒子到文档的距离 */
                    div1.style.left=e.clientX-arr+'px'
                    div1.style.top=e.clientY-arr2+'px'
                }
            }
            div1.onmouseup=function(){
                document.onmousemove=null
            } 
        </script>
    </body>