本文实例为大家分享了vue实现鼠标经过显示悬浮框效果的具体代码,供大家参考,具体内容如下
项目架构采用vue-cli脚手架搭建的webpack项目
实现的效果如下:
鼠标经过button 右边显示出一个悬浮框 鼠标移出buttom元素 悬浮框隐藏 并且悬浮框可以随着鼠标的移动而改变位置
全部代码如下:
<template> ? <div class="hello"> ? ? <div id="focus_tooltip" class="special_focus_tooltip" v-html="tooltopbody"></div> ? ? <button ? ? ? class="buttonstyle" ? ? ? @mousemove="itemmousemove($event)" ? ? ? @mouseover="itemmouseover" ? ? ? @mouseout="itemmouseout" ? ? >悬浮框测试</button> ? </div> </template> <script> import $ from "jquery"; export default { ? name: "helloworld", ? data() { ? ? return { ? ? ? tooltopbody: "" ? ? }; ? }, ? methods: { ? ? itemmouseover: function() { ? ? ? var focustooltip = $("#focus_tooltip"); ? ? ? focustooltip.css("display", "block"); ? ? }, ? ? itemmouseout: function() { ? ? ? var focustooltip = $("#focus_tooltip"); ? ? ? focustooltip.css("display", "none"); ? ? }, ? ? itemmousemove: function(e) { ? ? ? var self = this; ? ? ? var focustooltip = $("#focus_tooltip"); ? ? ? 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;'>" + ? ? ? ? "我的悬浮框参考:" + ? ? ? ? "</div>"; ? ? ? var effecthtml = ? ? ? ? "<div style='font-size:12px;margin-top:5px;'>" + "</div>"; ? ? ? self.tooltopbody = headerhtml + effecthtml; ? ? } ? } }; </script> <!-- add "scoped" attribute to limit css to this component only --> <style scoped> .buttonstyle { ? margin-left: 150px; } .special_focus_tooltip { ? z-index: 7; ? position: absolute; ? display: none; ? width: 400px; ? height: 130px; ? 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; } </style>
主要实现思路:
首先展示的悬浮框是绝对定位并且一开始是隐藏的display:none,触发 mouseover事情的时候把元素展示出来focustooltip.css(“display”, “block”); 触发itemmouseout事件的时候把它隐藏掉focustooltip.css(“display”, “none”); 然后当鼠标指针在指定的元素中移动时,就会发生 mousemove 事件, 这个时候通过event 对象拿到鼠标的位置(备注:event 对象代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态),然后稍微调整下位置,最后给悬浮框的div元素设置top 和left属性, 其实悬浮框是基于html定位的 他的父元素没有相对定位position: relative; 不然会影响到top和left的属性,因为absolute会基于父元素relative进行定位。 鼠标事件整体触发的顺序为mouseover->mousemove->mouseout 最后悬浮框里面的内容会根据v-html对应的内容渲染(这块展示的内容由自己定义)