vue组件和js实现鼠标悬停显示title效果

2023-11-02

需求:

显示文本内容过长,显示…鼠标悬浮时,全部显示

  • 使用element组件<el-tooltip offset="-2" class="item" effect="dark" placement="top"> <span class="dispatchSystemAddressBookItemText">{{item.name}}</span> <div slot="content"> <div class="dispatchSystemAddressBookItemText-totip"> {{item.name}} </div> </div> </el-tooltip>
  • 在这里插入代码片
<div class="dispatchSystemAddressBook-itemBox">
  <div
          :class="[dispatchSystemAddressBookItemText ,index === currentSystemAddressBookItem ? selectDispatchSystemAddressBookItemText : nomalDispatchSystemAddressBookItemText]"
          v-for="(item,index) in table1PannelTest"
          :key="item.id"
          @click="handleDispatchTabClick(item.id,index)">
      <template v-if="GlobalFunc.getStringLength(item.name)>6">
     <el-tooltip offset="-2" class="item" effect="dark" placement="top">
              <span class="dispatchSystemAddressBookItemText">{{item.name}}</span>
              <div slot="content">
                  <div class="dispatchSystemAddressBookItemText-totip">
                      {{item.name}}
                  </div>
              </div>

          </el-tooltip>


      </template>
      <template v-else>
          <span :title="item.name" class="dispatchSystemAddressBookItemText">{{item.name}}</span>
      </template>

  </div>
</div>

element组件效果

在这里插入图片描述
在这里插入图片描述

一、部分需求推荐方案 使用js自定义悬浮

  • 全局挂载函数
  • 新建元素,添加样式
  • 组件使用

这里我们把定义函数挂载到全局
在这里插入图片描述


/**
 * 鼠标悬停显示TITLE
 * @params     obj        当前悬停的标签
 *
 */
GlobalFunc.titleMouseOver=function titleMouseOver(event,words_per_line) {
  //无TITLE悬停,直接返回
  if(typeof event.target.title == 'undefined' || event.target.title == '') return false;
  //不存在title_show标签则自动新建
  var title_show = document.getElementById("title_show");
  if(title_show == null){
    title_show = document.createElement("div");                            //新建Element
    document.getElementsByTagName('body')[0].appendChild(title_show);    //加入body中
    var attr_id = document.createAttribute('id');                        //新建Element的id属性
    attr_id.nodeValue = 'title_show';                                    //为id属性赋值
    title_show.setAttributeNode(attr_id);                                //为Element设置id属性
    document.getElementById("title_show").classList.add("title_focus_toolTip");//为为Element添加类属性
    var attr_style = document.createAttribute('style');                    //新建Element的style属性
    attr_style.nodeValue = 'position:absolute;'                            //绝对定位
      /*  +'border:solid 1px #f3f3f3; background:rgba(50, 50, 50, 0.701961)'                //边框、背景颜色
        +'top:-50%'                //边框、背景颜色
        +'border-radius:2px;box-shadow:0px 0px 2px #ccc;'                //圆角、阴影
        +'line-height:30px!important;'                                            //行间距
        +'font-size:18px; padding: 2px 5px;';                            //字体大小、内间距*/
    try{
      title_show.setAttributeNode(attr_style);                        //为Element设置style属性
    }catch(e){
      //IE6
      // title_show.style.position = 'absolute';
      // title_show.style.border = 'solid 1px #f3f3f3';
      // title_show.style.background = 'rgba(50, 50, 50, 0.701961)';
      // title_show.style.lineHeight = '20px';
      // title_show.style.fontSize = '30px';
      // title_show.style.padding = '2px 5px';
      document.getElementById("title_show").classList.add("title_focus_toolTip");//为为Element添加类属性
    }
  }
  //存储并删除原TITLE
  document.title_value = event.target.title;
  event.target.title = '';
  //单行字数未设定,非数值,则取默认值50
  if(typeof words_per_line == 'undefined' || isNaN(words_per_line)){
    words_per_line = 50;
  }
  //格式化成整形值
  words_per_line = parseInt(words_per_line);
  //在title_show中按每行限定字数显示标题内容,模拟TITLE悬停效果
  title_show.innerHTML = GlobalFunc.split_str(document.title_value,words_per_line);
  //显示悬停效果DIV
  title_show.style.display = 'block';

  //根据鼠标位置设定悬停效果DIV位置
  event = event || window.event;                            //鼠标、键盘事件
  var top_down = 50;                                        //下移15px避免遮盖当前标签
  //最左值为当前鼠标位置 与 body宽度减去悬停效果DIV宽度的最小值,否则将右端导致遮盖
  var left = Math.min(event.clientX,document.body.clientWidth-title_show.clientWidth);
  title_show.style.left = left+"px";            //设置title_show在页面中的X轴位置。
  title_show.style.top = (event.clientY - top_down)+"px";    //设置title_show在页面中的Y轴位置。
  // title_show.style.top = top_down+"%";    //设置title_show在页面中的Y轴位置。
}
/**
 * 鼠标离开隐藏TITLE
 * @params    obj        当前悬停的标签
 *
 */
GlobalFunc.titleMouseOut= function titleMouseOut(event) {
  var title_show = document.getElementById("title_show");
  //不存在悬停效果,直接返回
  if(title_show == null) return false;
  //存在悬停效果,恢复原TITLE
  event.target.title = document.title_value;
  //隐藏悬停效果DIV
  title_show.style.display = "none";
}
/**
 * className 类名
 * tagname HTML标签名,如div,td,ul等
 * @return Array 所有class对应标签对象组成的数组
 * @example
 <div class="abc">abc</div>
 var abc = getClass('abc');
 for(i=0;i<abc.length;i++){
     abc[i].style.backgroundColor='red';
 }
 */
GlobalFunc.getClass= function getClass(className,tagname) {
  //tagname默认值为'*',不能直接写成默认参数方式getClass(className,tagname='*'),否则IE下报错
  if(typeof tagname == 'undefined') tagname = '*';
  if(typeof(getElementsByClassName) == 'function') {
    return getElementsByClassName(className);
  }else {
    var tagname = document.getElementsByTagName(tagname);
    var tagnameAll = [];
    for(var i = 0; i < tagname.length; i++) {
      if(tagname[i].className == className) {
        tagnameAll[tagnameAll.length] = tagname[i];
      }
    }
    return tagnameAll;
  }
}
/**
 * JS字符切割函数
 * @params     string                原字符串
 * @params    words_per_line        每行显示的字符数
 */
GlobalFunc.split_str= function split_str(string,words_per_line) {
  //空串,直接返回
  if(typeof string == 'undefined' || string.length == 0) return '';
  //单行字数未设定,非数值,则取默认值50
  if(typeof words_per_line == 'undefined' || isNaN(words_per_line)){
    words_per_line = 50;
  }
  //格式化成整形值
  words_per_line = parseInt(words_per_line);
  //取出i=0时的字,避免for循环里换行时多次判断i是否为0
  var output_string = string.substring(0,1);
  //循环分隔字符串
  for(var i=1;i<string.length;i++) {
    //如果当前字符是每行显示的字符数的倍数,输出换行
    // if(i%words_per_line == 0) {
    //     output_string += "<br/>";
    // }
    //每次拼入一个字符
    output_string += string.substring(i,i+1);
  }
  return output_string;
}

/**
 * 悬停事件绑定
 * @params    objs        所有需要绑定事件的Element
 *
 */
GlobalFunc.attachEvent= function attachEvent(objs,words_per_line){
  if(typeof objs != 'object') return false;
  //单行字数未设定,非数值,则取默认值50
  if(typeof words_per_line == 'undefined' || isNaN(words_per_line)){
    words_per_line = 10;
  }
  for(let i=0;i<objs.length;i++){
    objs[i].onmouseover = function(event){
      GlobalFunc.titleMouseOver(this,event,words_per_line);
    }
    objs[i].onmouseout = function(event){
      GlobalFunc.titleMouseOut(this);
    }
  }
}


使用:

    <div title="实现悬停实现悬停的TITLE"
         @mouseenter="GlobalFunc.titleMouseOver($event,15)"
         @mouseleave="GlobalFunc.titleMouseOut($event)"
    >鼠标悬停[直接调用函数版本,设定行字数]</div>
   <style>
    .title_focus_toolTip {
        z-index: 7;
        position: absolute;
        display: none;
        min-width: 200px;
        min-height: 50px;max-width: 200px;word-break: normal;
        border-style: solid;
        transition: left 0.4s cubic-bezier(0.23, 1, 0.32, 1),
        top 0.4s cubic-bezier(0.23, 1, 0.32, 1);
        background-color: rgba(50, 50, 50, 0.701961);
        border-width: 0px;
        border-color: #333333;
        border-radius: 4px;
        color: #ffffff;
        font-style: normal;
        font-variant: normal;
        font-weight: normal;
        font-stretch: normal;
        font-size: 14px;
        font-family: "Microsoft YaHei";
        line-height: 21px;
        padding: 10px 10px;
        z-index: 9999;
        pointer-events: none;
    }
    
</style>

效果:
在这里插入图片描述

二、方案2 我们也可以写简单一点

定义一个div,作为弹框,需要显示传入内容即可

  <div id="focus_toolTip" class="special_focus_toolTip" v-html="dispatchSystemAddressBookTopbody">
                            </div>
 .special_focus_toolTip {
        z-index: 7;
        position: absolute;
        display: none;
        /*min-width: 200px;*/
        min-height: 80px;
        max-width: 200px;
        word-break: normal;
        border-style: solid;
        transition: left 0.4s cubic-bezier(0.23, 1, 0.32, 1),
        top 0.4s cubic-bezier(0.23, 1, 0.32, 1);
        background-color: rgba(50, 50, 50, 0.701961);
        border-width: 0px;
        border-color: #333333;
        border-radius: 4px;
        color: #ffffff;
        font-style: normal;
        font-variant: normal;
        font-weight: normal;
        font-stretch: normal;
        font-size: 14px;
        font-family: "Microsoft YaHei";
        line-height: 21px;
        padding: 10px 10px;
        z-index: 9999;
        pointer-events: none;
    }

鼠标事件

 <span  @mouseenter="GLOBALItemMouseover($event,'focus_toolTip',item.name) "
                                                          @mouseleave ="dispatchSystemAddressBookGLOBALIitemMouseout('focus_toolTip')" class="dispatchSystemAddressBookItemText" >{{item.name}}</span>

全局自定义事件

   GLOBALItemMouseover(e,id,name){
        this.dispatchSystemAddressBookTopbody = this.GlobalFunc.GLOBALItemMouseover(e,id,name);
      },
      dispatchSystemAddressBookGLOBALIitemMouseout(id){
      this.GlobalFunc.GLOBALIitemMouseout(id);
      },
/**
 * 自定义鼠标悬浮弹框
 */
GlobalFunc.GLOBALItemMouseover=(e,toolTipId,name)=> {
  var focusTooltip = $("#"+toolTipId);
  focusTooltip.css("top", e.clientY -140+ "px");
  focusTooltip.css("left", e.clientX + "px");
  var headerHtml =
      "<div style='font-size:14px;color: #ffffff;font-weight: bold;font-family: MicrosoftYaHei;pointer-events: none'>" +
      name +
      "</div>";
  var effectHtml =
      "<div style='font-size:12px;margin-top:5px;pointer-events: none'>" + "</div>";
  let params = headerHtml + effectHtml;
  GlobalFuncDasConstants.setToolTopbody(name);
  console.log(GlobalFuncDasConstants.aaoolTopbody);
  GlobalFunc.ttoolTopbody = params;
  focusTooltip.css("display", "block");
  return params;
}
/**
 * 自定义鼠标悬浮弹框关闭
 */
GlobalFunc.GLOBALIitemMouseout=function GLOBALIitemMouseout(toolTipId) {
  var focusTooltip = $("#"+toolTipId);
  focusTooltip.css("display", "none");
}
/**
 * 自定义鼠标移动
 */
GlobalFunc.GLOBALItemMousemove=function  GLOBALItemMousemove(e,toolTipId,name) {
  var self = this;
  var focusTooltip = $("#"+toolTipId);
  focusTooltip.css("top", e.clientY - 80 + "px");
  focusTooltip.css("left", e.clientX + 100 + "px");
  var headerHtml =
      "<div style='font-size:12px;color: #fec443;font-weight: bold;font-family: MicrosoftYaHei;'>" +
      name +
      "</div>";
  var effectHtml =
      "<div style='font-size:12px;margin-top:5px;'>" + "</div>";
  let params = headerHtml + effectHtml;
  return params;
}

自定义效果

在这里插入图片描述

三、这里存在闪动问题

照成的原因是:悬停上去信息框div盖住了span标签,mouseover事件失效,mouseout事件生效,信息框消失。
信息框消失后鼠标又正好悬停在span标签上,mouseover事件生效,mouseout事件失效,信息框显示。。。一直无限循环就会看到一直闪烁的现象。

解决办法 :在你需要显示的信息框上加上pointer-events: none

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

vue组件和js实现鼠标悬停显示title效果 的相关文章

随机推荐

  • 防止Sql注入拦截

    这两天在做一个sql注入拦截 期间遇到了不少问题 最大的问题是在 拦截sql注入后利用response 重定向到错误页面 始终无法实现跳转 发现原因是 ajax 异步请求时并不会对response重定向做处理 当然包括response ge
  • vite 配置路径别名@和动态引入assets资源

    vite 配置路径别名 vite config js配置 import fileURLToPath URL from node url 如果是ts 则需下载 types node以来 import defineConfig from vit
  • 解决socket.error: [Errno 98] Address already in use问题

    一 基本设置 如果python中socket 绑定的地址正在使用 往往会出现错误 在linux下 则会显示 socket error Errno 98 Address already in use 在windows下 则会显示 socket
  • linux访问有域名的ftp,Linux安装了ftp服务怎么用域名访?

    ftp directory怎么配置根 请自行准备好华为交换机和电脑 并且让你的电脑和交换机连接上 不管是telnet还是terminal都是可以的 首先需要在 Quidway 下启动ftp服务 Quidway ftp server enab
  • GPU比较(1285Lv4&1245v5)

    1285Lv4 Intel Iris Pro Graphics P6300 Iris Graphics 6200 P6300 EU 48 核心代号 GT3e 1245v5 HD Graphics P530 EU 48 核心代号 GT3e
  • 网络安全面试题

    IT面试 前言 首先 从底层的环境 计算机基础 即网络 系统方面开始 网络从交换 路由的基本认知到排错 系统从命令查看方面 其次 最后 通过编程语言 如python 提供自动化运维的方法 提高办公 简历方面 专业技能模块可以写成 1 熟悉网
  • sql-labs闯关26~31

    sql labs闯关26 31 友善爱国平等诚信民主富强爱国友善自由友善爱国平等诚信民主爱国爱国爱国 复习笔记1 第29 31关先跳过 回头再做 内容 sql labs第26关 GET请求 基于错误 过滤空格和注释 sql labs第26a
  • 报错解决:PermissionError

    在linux环境中安装jupyter notebook的时候遇到的错误 记录一下 PermissionError Errno 13 Permission denied run user 1002 jupyter 解决办法 chmod 777
  • 一文读懂深度学习中的矩阵微积分

    点击上方 小白学视觉 选择加 星标 或 置顶 重磅干货 第一时间送达 本文转自 视学算法 想要真正了解深度神经网络是如何训练的 免不了从矩阵微积分说起 虽然网络上已经有不少关于多元微积分和线性代数的在线资料 但它们通常都被视作两门独立的课程
  • 双向LSTM 对航空乘客预测

    前言 1 LSTM 航空乘客预测 单步预测和多步预测 简单运用LSTM 模型进行预测分析 2 加入注意力机制的LSTM 对航空乘客预测采用了目前市面上比较流行的注意力机制 将两者进行结合预测 3 多层 LSTM 对航空乘客预测 简单运用多层
  • cmd 用命令连接oracle数据库

    这里所用的数据库在tnsnames ora里的配置 mesdb155 DESCRIPTION ADDRESS PROTOCOL TCP HOST IP地址 PORT 端口号 CONNECT DATA SERVER XXX SERVICE N
  • Spring之Joinpoint类详解

    说明 Joinpoint是AOP的连接点 一个连接点代表一个被代理的方法 我们从源码角度看连接点有哪些属性和功能 源码 Copyright 2002 2016 the original author or authors Licensed
  • CentOS7安装Keepalived详细步骤

    1 首先先去Keepalived官网上下载 官网地址 2 把下载好的Keepalived压缩包上传到我们的CentOS7系统上 然后输入下面解压命令进行解压 tar zxvf keepalived 2 0 18 tar gz 3 先进入Ke
  • 7 - 简单状态机代码设计

    7 简单状态机代码设计 三角波发生器 代码 2021 11 21 lyw The simplest state machine triangle wave generator timescale 1ns 10ps module tri ge
  • 记一次使用hive-jdbc+tomcat-jdbc连接(Connection)中断的处理过程

    现象描述 Hive环境一个数据库 拥有表8000 业务代码需要挨个desc tableName 来获取表信息 当程序运行到4000 左右 开始出现获取信息失败 查找原因 通过查看日志发现是连接已断开 具体如下 INFO org apache
  • Kaggle——Rain in Australia (Predict rain tomorrow in Australia)

    文章目录 写在前面 1 案例背景 2 解读数据 2 导入数据进行数据分析及特征工程 2 1 概览数据 2 2 探索数据 2 2 1 探索数据类型 2 2 2 探索缺失值 2 2 3 产生训练集和测试集 2 2 4 分析是否存在样本不平衡问题
  • 在笔试题面试题中,如果出现加法和乘法,要注意是否越界的问题

    比如不设置另外变量 a和b如何置换 一法为相加的方法 可能越界 二法为异或法 程序员面试宝典也有此题 再比如类似问题是华为上机试题 如何求整数数组中大于平均值的个数 如果最用求平均值的方法 就会出现浮点数 为避免出现浮点数 可以转化为总和与
  • java基础(三)数组字典,类与对象

    字符串去重 public class Test04 public static void removeMrthod String s StringBuffer sb new StringBuffer boolean flag false f
  • gradle-5.6.4-all 百度网盘下载CSDN快速下载

    Gradle 5 6 4 发布 Gradle团队很兴奋地宣布Gradle 5 6 4 此版本的特点是提高Groovy编译速度的改进 的新插件Java测试夹具和更好地管理插件版本在多项目构建中 这是Gradle 5 x的最终次要版本 还有许多
  • vue组件和js实现鼠标悬停显示title效果

    需求 显示文本内容过长 显示 鼠标悬浮时 全部显示 使用element组件