首先说明一下效果: 鼠标放到头像上面左边会显示一块个人资料框, 离开头像后过一小段时间个人资料信息消失, 离开头像后如果鼠标放在个人资料框上面则个人资料框不消失; html 代码: 一个 id 为 head 的标签和一个 id 为 left 的标签 这两个就足以完成下来的效果;
- #head 相当于头像;#left 相当于个人资料框 (一开始是隐藏的 display:none;);CSS 样式就不写了, 直接写 js 原生 js: 首先获取 dom 节点
- var Head = document.getElementById("head");
- var Left = document.getElementById("left");
有鼠标的移入移出动作 所以要用到 onmouseover(鼠标移入) 和 onmouseout(鼠标移出) 两个事件 先来写移入事件:
- Head.onmouseover = function(){
- Left.style.display = "block";
- }
鼠标放在 Head 上面则 Left 显示 添加 css 属性 display:block;
下来要分析一下了: 鼠标离开头像之后 Left 不能立即消失, 所以这块要用到延时器 (setTimeout) ; 鼠标离开头像之后我们还要做一个判断 鼠标是否移入了 Left, 所以要做一个开关 (就是给一个变量进行判断) 先从简单的来写一点点往上加, 先不做是否移入 Left 判断那么移出 Head 应该这么写:
- Head.onmouseout = function(){
- setTimeout(function(){ // 延时一秒让 Left 消失
- Left.style.display = "none";
- },1000);
- }
下来我们就要写开关了 判断鼠标离开头像之后是否进入 Left
- var isIndom = false; // 给一个变量 用它来模拟开关 通过判断变量我们就可以知道鼠标是否移入 Left
- Left.onmouseover = function(){ // 如果鼠标移入 Left 则将 isIndom 改为 true
- isIndom = true;
- }
- Left.onmouseout = function(){ // 鼠标移出 Left 则将 isIndom 改为 flase 并将 Left 隐藏 this 指向 Left
- isIndom = false;
- this.style.display = "none";
- }
最后要给 Head 的鼠标移出事件里面加上判断就可以了 在 inIndom == flase 的时候选择隐藏 Head
- Head.onmouseout = function(){
- setTimeout(function(){ // 延时一秒让 Left 消失
- if(!isIndom){
- Left.style.display = "none";
- }
- },1000);
- }
上面就是原生 js 写的延时提醒框 下来用 jq 写一个同样的效果 在 jq 中鼠标移入移出事件分别是 mouseover() mouseout();
- $("#head").mouseover(function(){ //$() 获取节点
- $("#left").fadeIn(2000); //fadeIn 是 jq 一个显示效果 (渐现) 也是为了让 Head 显示只是方式不同而已
- })
下来还是要写一个开关 这次我们将开关封装起来
- var isIndom = flase; // 定义全部变量 isIndom(开关)
- function switch0(){
- $("#left").mouseover(function(){
- isIndom = true;
- });
- $("#left").mouseout(function(){
- isIndom = false;
- $("#left").fadeOut(1000);
- });
- }
switch0 函数所执行出来的 isIndom 就是我们要的值
最后写鼠标移出 Head 事件
- $("#head").mouseout(function(){
- switch0(); // 先执行 switch0 函数 得到 isIndom 的值
- setTimeout(function(){
- if(!isIndom){
- $("#left").fadeOut(1000); //fadeOut() 和 fadeIn() 对应是 jq 一个消失的效果 (渐隐)
- }
- },1000);
- })
来源: https://juejin.im/post/5a9f5cad51882555867eefac