鼠标悬停的数据突出高亮显示

244 阅读2分钟

前言

公司项目需要实现鼠标放在数据上时数据突出高亮显示。我第一想法是直接绑定鼠标悬停事件,然后改字体大小就行了。但是需要的数量太多了,所以我就写了个监听事件,在内部处理这部分逻辑

解决方案

  1. 通过 document.getElementsByClassName("mouseHoverEnlarge") 获取所有具有类名 "mouseHoverEnlarge" 的元素,将它们存储在 mouseHoverEnlargeArr 数组中。
  2. 使用 for 循环遍历 mouseHoverEnlargeArr 数组中的每个元素。
  3. 对于每个元素,首先尝试获取它的 fontSizefontWeight 样式属性值,存储在变量 fontSizefontWeight 中。这里使用 element.style.fontSizeelement.style.fontWeight 尝试获取样式属性值,但这些属性值可能为空(如果样式是通过 CSS 设置的)。
  4. 使用 window.getComputedStyle(element) 获取计算后的样式,以确保获取到正确的样式属性值。将 font-size 样式属性的值存储在 oldfontSize 变量中。
  5. oldfontSize 中截取前两位字符,并将其转换为数字类型,然后加上 5,以计算新的字体大小,并将结果存储在 newfontSize 变量中。
  6. 为当前元素添加 mouseover 事件监听器,当鼠标悬停在元素上时触发。在事件处理程序中,将元素的 fontSize 设置为新的字体大小 newfontSize,并将 fontWeight 设置为 "bold",以实现突出显示的效果。
  7. 为当前元素添加 mouseout 事件监听器,当鼠标移出元素时触发。在事件处理程序中,将元素的 fontSizefontWeight 还原为初始值,以还原样式。
<template>
  <div>
     <!-- 标签加上类名进行识别 -->
    <p class="mouseHoverEnlarge">{{ elementsRen.zongrenshu }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  mounted() {
    // 获取具有类名 "mouseHoverEnlarge" 的所有元素
    let mouseHoverEnlargeArr =document.getElementsByClassName("mouseHoverEnlarge");

    // 遍历每个元素
    for (let i = 0; i < mouseHoverEnlargeArr.length; i++) {
      const element = mouseHoverEnlargeArr[i];

      // 尝试获取元素的 fontSize 和 fontWeight 属性值(可能为空)
      let fontSize = element.style.fontSize;
      let fontWeight = element.style.fontWeight;

      // 使用 getComputedStyle 获取计算后的样式以确保获取正确的值
      let computedStyle = window.getComputedStyle(element);
      let oldfontSize = computedStyle.getPropertyValue("font-size");

      // 截取前两位并加上 5 以确定新的字体大小
      let newfontSize = parseInt(oldfontSize.substring(0, 2)) + 5;

      // 添加鼠标悬停事件监听器
      element.addEventListener("mouseover", () => {
        // 设置新的字体大小和粗细以突出显示
        element.style.fontSize = newfontSize + "px";
        element.style.fontWeight = "bold";
      });

      // 添加鼠标移出事件监听器
      element.addEventListener("mouseout", () => {
        // 还原字体大小和粗细为初始值
        element.style.fontSize = fontSize;
        element.style.fontWeight = fontWeight;
      });
    }
  },
};
</script>