前言
接到一个需求,是在文章详情中鼠标左键选中一段文字,然后在文字后面弹出按钮,按钮5秒后消失,点击按钮,得到文字内容传给后端。以下记录实现方案:
技术栈:vue2
一、选择事件(使用mouseup)
二、判断mouseup事件触发时,是否有选中内容
三、按钮位置以及显示隐藏
四、代码
1.html
代码如下:
<template>
<div @mouseup="handleMouseUp">{{content}}</div>
<div v-show="visible" :style="{ left: left + 'px', top: top + 'px', position: 'fixed', }" class="contextMenu">
摘录
</div>
</template>
2.js
实现代码如下:
export default {
data() {
return {
visible: false,
selectStr: '',
}
},
methods: {
handleMouseUp(event) {
//选中的文字
this.selectStr = window.getSelection().toString();
//判断是否选择了文字
if (this.selectStr) {
//获取鼠标事件位置
let x = event.clientX;
let y = event.clientY;
this.top = y;
this.left = x;
//显示按钮
this.visible = true;
//倒计时
setTimeout(() => {
this.selectStr = ''
this.visible = false;
}, 5000)
}else {
this.visible = false;
}
},
}
}
总结
提醒自己记住事件选择方式和获取位置方式