element dropdown实现小记
一。为什么我会想看element如何实现的 dropdown?
上面是element dropdown显示时的效果,看到那个红色标注的地方吗? 如果你把鼠标移动到那里, 过一会之后,这个下拉菜单就会消失。这是为什么?难道我以前实现下拉菜单的方式现在不能用了?如果能用,那移动到标红的那里,下拉菜单应该不会消失才对。如果是采用别的方案(我以前也通过js实现过这种效果,但那需要用到relatedTarget属性
,判断当前到底是移动到那个dom上面了,然后决定是否隐藏),看效果element好像也是这样,可是中间隔了一段,那应该就没法实现了呀,难道用定时器延迟一会(个人对定时器是有点抵触的),再进行relatedTarget
的判断? 就算这样能实现,应该也难以通用啊。心痒难耐,遂需要查看源码一探究竟。
二。我以前是怎么实现hover效果的下拉菜单?
原理:
// 定义类似这样的html结构 .dropDown > dropDownTitle > ul >li >li // ul默认隐藏 // 在dropDown中加入伪类 :hover, 在这个伪类触发时, 显示ul 复制代码
代码大概是这样:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body,html{ margin:0; } ul,li{ margin:0; list-style-type: none; padding:0; } .dropDown{ width: 200px; } .dropDownTitle{ background-color: lightgoldenrodyellow; } .dropDown:hover > ul{ display: block; } ul{ display: none; margin-top:10px; background-color: lightblue; } </style> </head> <body> <div class="dropDown"> <div class="dropDownTitle">菜单</div> <ul> <li>菜单1</li> <li>菜单2</li> <li>菜单3</li> </ul> </div> </body> </html> 复制代码
三。element到底是怎么实现的?走,去看看。
源码路径: element-ui/packages/dropdown.vue
代码截选:
....省略很多代码 show() { if (this.disabled) return; /* 清除尚未执行的定时器, 这里的主要作用应该是为了避免在移出按钮,移入到下拉菜单时, 下拉菜单先被隐藏,然后再被显示的问题 */ clearTimeout(this.timeout); console.log('show clearTimeout之后',this,this.name) // 之所以通过定时器方式设置显示,应该是为了避免,鼠标不经意扫过时,下拉菜单闪现的问题 this.timeout = setTimeout(() => { this.visible = true; }, this.trigger === 'click' ? 0 : this.showTimeout); }, hide() { if (this.disabled) return; console.log(this.disabled, new Date().toLocaleTimeString()) this.removeTabindex(); console.log('removeTabindex已执行') if (this.tabindex >= 0) { this.resetTabindex(this.triggerElm); } console.log('clearTimeout之前') clearTimeout(this.timeout); console.log('clearTimeout之后') // 之所以通过定时器方式设置隐藏,应该是为了给鼠标从按钮移入到下拉菜单留时间,不然,鼠标一移出按钮,下拉菜单就消失了 this.timeout = setTimeout(() => { console.log('this.visible',this.visible) this.visible = false; }, this.trigger === 'click' ? 0 : this.hideTimeout); console.log('setTimeout之后',this.trigger === 'click' ? 0 : this.hideTimeout,this.timeout) }, initEvent(){ ....省略很多代码 if (trigger === 'hover') { /* 在那个按钮上注册鼠标移入/移出事件, 移入时调用show方法将变量visible设置为true表示显示下拉菜单, 移出时调用hide方法将变量visible设置为false表示隐藏下拉菜单, */ this.triggerElm.addEventListener('mouseenter', show); this.triggerElm.addEventListener('mouseleave', hide); /* 在下拉菜单上注册鼠标移入/移出事件, 移入时调用show方法将变量visible设置为true表示显示下拉菜单,同时移除设置隐藏的定时器, 移出时调用hide方法将变量visible设置为false表示隐藏下拉菜单, */ dropdownElm.addEventListener('mouseenter', show); dropdownElm.addEventListener('mouseleave', hide); } else if (trigger === 'click') { this.triggerElm.addEventListener('click', handleClick); } }, ....省略很多代码 } ....省略很多代码
作者:悟空和大王
链接:https://juejin.cn/post/7023263126581673992