• 判断页面的点击事件是否发生在某元素上


    本文地址:https://www.cnblogs.com/veinyin/p/10999265.html 

    有时我们需要判断页面的点击事件是否发生在某元素上

    使用场景如  自己实现下拉框  点击页面其它地方时下拉部分隐藏

    下面代码为 vue 场景下

    // template 中
    div(ref="myDiv")
    
    // created 中添加 click 事件句柄  判断点击事件是否发生在某元素上
    document.addEventListener('click', event => {
        const e = event || window.event
        if (this.$refs.myDiv && !this.$refs.myDiv.contains(e.target)) {
            console.log('not in myDiv')
        }
    })

    如果是非全局组件  需要在 beforeDestroy 中移除事件句柄  

    此时需要在 methods 中写一个具名函数   第二个参数为该函数名

    // 添加事件句柄
    created() {
        document.addEventListener('click', myFunc)
    },
    
    // 移除事件句柄
    beforeDestroy () {
        document.removeEventListener('click', myFunc)
    },
    
    // 相应函数
    methods: {
        myFunc(event) {
            // 同上
        } 
    }

    END~~~≥ω≤

  • 相关阅读:
    2015多校.Zero Escape (dp减枝 && 滚动数组)
    UVa-11809
    UVa-1588 Kickdown
    UVa-1587
    UVa-10340
    UVa-202
    UVa-1368
    UVa-232 Crossword Answers
    UVa-227
    UVa-455 Periodic Strings
  • 原文地址:https://www.cnblogs.com/veinyin/p/10999265.html
Copyright © 2020-2023  润新知