最近一个项目,选中某些文本,然后右键进行一些操作,使用了vue-contextmenujs插件
-
安装vue-contextmenujs
npm install vue-contextmenujs
-
mian.js中引用该组件
import Contextmenu from 'vue-contextmenujs';
Vue.use(Contextmenu); -
页面中使用
4.判断是否在该文本区域内
rightClick(event) {
console.log("点击了右键", event);
this.chapterText = ""; // 先清空,chapterText 保存选中文本
let sel = window.getSelection
? window.getSelection()
: document.selection.createRange();
let text = sel.toString();
if (!text) {
return false;
}
let divId = "bodyContainer";
if (sel.getRangeAt) {
var range = sel.getRangeAt(0);
var ancestor = range.commonAncestorContainer;
while (
ancestor.id != divId && // Check id, class or otherwise
ancestor.parentElement != null
) {
ancestor = ancestor.parentElement;
}
if (ancestor.id == divId) {
// Selection is within the editor.
console.log("在div内");
this.chapterText = window.getSelection().toString();
this.$contextmenu({
items: this.rightMenuData,
event, // 鼠标事件信息
customClass: "custom-class", // 自定义菜单 class
zIndex: 3, // 菜单样式 z-index
minWidth: 150, // 主菜单最小宽度
});
} else {
console.log("不在div内");
return false;
}
} else {
//
return false;
}
return false;
},
5.菜单
rightMenuData: [
{
label: "翻译",
onClick: () => {
this.handleTranslate();
},
},
....
},
],