您现在的位置是:网站首页> 编程资料编程资料
vue自定义指令添加跟随鼠标光标提示框v-tooltip方式_vue.js_
2023-05-24
313人已围观
简介 vue自定义指令添加跟随鼠标光标提示框v-tooltip方式_vue.js_
自定义指令添加跟随鼠标光标提示框v-tooltip
在vue中添加自定义指令,能够识别dom,通过鼠标hover事件移入当前区域后,显示浮层
1、directives自定义提示指令
directives: { // 自定义提示指令 tooltip: { componentUpdated: function(el, binding) { // 鼠标移入时,将浮沉元素插入到body中 el.onmouseenter = function(e) { // 创建浮层元素并设置样式 const vcTooltipDom = document.createElement('div'); vcTooltipDom.style.cssText = ` overflow: auto; position:absolute; background: #fff;; color:#666; box-shadow: rgba(168, 168, 168, 0.295) 1px 2px 10px; border-radius:5px; padding:10px; display:inline-block; font-size:14px; z-index:2 `; // 设置id方便寻找 vcTooltipDom.setAttribute('id', 'vc-tooltip'); // 将浮层插入到body中 document.body.appendChild(vcTooltipDom); // 浮层中的文字 通过属性值传递动态的显示文案 document.getElementById('vc-tooltip').innerHTML = el.getAttribute('tips'); }; // 鼠标移动时,动态修改浮沉的位置属性 el.onmousemove = function(e) { const vcTooltipDom = document.getElementById('vc-tooltip'); vcTooltipDom.style.top = e.clientY + 15 + 'px'; vcTooltipDom.style.left = e.clientX + 15 + 'px'; }; // 鼠标移出时将浮层元素销毁 el.onmouseleave = function() { // 找到浮层元素并移出 const vcTooltipDom = document.getElementById('vc-tooltip'); vcTooltipDom && document.body.removeChild(vcTooltipDom); }; } } }通过监听鼠标移入移出的mouse方法,设置浮层样式与出现时机
2、div显示dom标签v-tooltip
此时运行后,出现浮层
vue自定义指令实现tooltip功能
1、需求
元素展示提示框跟随鼠标移动
2、思路
vue的自定义指令
将显示内容放到容器中,通过值传递,监听鼠标移入事件,鼠标移入后将容器append到body
- 监听鼠标移动事件,根据鼠标的e.clientY,e.clientX修改容器位置
- 监听鼠标移出事件,销毁容器
3、代码
// 自定义提示指令 directives: { tooltip(el, binding){ // 鼠标移入时,将浮沉元素插入到body中 el.onmouseenter = function (e) { // 创建浮层元素并设置样式 const vcTooltipDom = document.createElement("div"); vcTooltipDom.style.cssText = ` position:absolute; background: #fff;; color:#fff; font-size:14px; z-index:1000 ; // 设置id方便寻找 vcTooltipDom.setAttribute("id", "vc-tooltip"); // 将浮层插入到body中 document.body.appendChild(vcTooltipDom); // 浮层中的文字 通过属性值传递动态的显示文案 document.getElementById("vc-tooltip").innerHTML = el.getAttribute("tips"); }; // 鼠标移动时,动态修改浮沉的位置属性 el.onmousemove = function (e) { const vcTooltipDom = document.getElementById("vc-tooltip"); vcTooltipDom.style.top = e.clientY + 15 + "px"; vcTooltipDom.style.left = e.clientX + 15 + "px"; }; // 鼠标移出时将浮层元素销毁 el.onmouseleave = function () { // 找到浮层元素并移出 const vcTooltipDom = document.getElementById("vc-tooltip"); vcTooltipDom && document.body.removeChild(vcTooltipDom); }; }, },4、在元素上使用
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- vue项目如何实现Echarts在label中获取点击事件_vue.js_
- Vue虚拟dom被创建的方法_vue.js_
- vue计算属性computed方法内传参方式_vue.js_
- vue项目中轮询状态更改方式(钩子函数)_vue.js_
- 关于vue文件中index.vue的使用方法_vue.js_
- 详解Vue3 SFC 和 TSX 方式调用子组件中的函数_vue.js_
- ant-design-vue中的table自定义格式渲染解析_vue.js_
- React 模块联邦多模块项目实战详解_React_
- ant-design-vue中设置Table每页显示的条目数量方式_vue.js_
- Ant Design Vue中的table与pagination的联合使用方式_vue.js_
