打开有些网站显示建设中,五个常见的电子商务网站,南京免费自助建站模板,WordPress数据库经常要重启监听当前元素之外的点击事件 一、具体场景二、具体实现三、完整代码 一、具体场景
当我们需要实现点击其他位置关闭弹窗的时候#xff0c;就需要监听当前元素之外的点击事件。
二、具体实现
实现思路#xff1a;监听整个dom的点击事件#xff0c;判断当前元素是否包含点击… 监听当前元素之外的点击事件 一、具体场景二、具体实现三、完整代码 一、具体场景
当我们需要实现点击其他位置关闭弹窗的时候就需要监听当前元素之外的点击事件。
二、具体实现
实现思路监听整个dom的点击事件判断当前元素是否包含点击事件的触发元素即可。 核心代码 const current document.getElementById(current) // 当前元素document.addEventListener(click, (e) {console.log(current.contains(e.target)) // 判断当前元素是否包含触发点击事件的元素如果当前元素有多个用 || 来判断即可})三、完整代码
!DOCTYPE html
html langen
headmeta charsetUTF-8titleTitle/titlestyle.box {width: 100px;height: 80px;border: 1px solid #000;}.current {width: 100%;height: 60px;background: #9A6AFF;}.child {width: 100%;height: 40px;background: #46E3B7;}/style
/head
body
div classboxdiv idcurrent classcurrent onclickcurrentClick()currentdiv classchild onclickchildClick()child/div/div
/div
scriptconst current document.getElementById(current)function currentClick() {console.log(current-click)}function childClick() {console.log(child-click)}document.addEventListener(click, (e) {console.log(current.contains(e.target))})
/script
/body
/html即使点击子元素也能被我们判断到。