gpt4 book ai didi

javascript - 如何在javascript中自定义右键单击选项?

转载 作者:行者123 更新时间:2023-12-02 16:46:31 24 4
gpt4 key购买 nike

我有一个包含内容的文本框。我只需要这样,当我选择文本并右键单击时,应根据所选文本弹出相应的(引用)列表。

例如。在文章中,会有“这是由(williams,2012)引用的”。如果我选择 Williams 并右键单击 ,则名称为 williams 的引用列表应作为弹出窗口列出。

JavaScript 代码:

if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
alert("You've tried to open context menu"); //here you draw your own menu
e.preventDefault();
}, false);
} else {
document.attachEvent('oncontextmenu', function() {
alert("You've tried to open context menu");
window.event.returnValue = false;
});
}

HTML:

<body>
Lorem ipsum...
</body>

此代码来自jsfiddle

现在,我只使用这段代码,我不知道如何根据我的要求构建它。当右键单击所选文本时,如何弹出适当的列表。请帮忙!

最佳答案

你应该做这样的事情。

function customContextAction(e){
var posX = e.x || e.clientX || e.layerX || e.offsetX || e.pageX, //gets the event position X
posY=e.y || e.clientY || e.layerY || e.offsetY || e.pageY; //gets the event position Y
var selectedText=window.getSelection().toString() || "";
var ctx = document.getElementById('context');
if (ctx.className.toLowerCase().indexOf("hidden") >= 0){
ctx.className="";
ctx.setAttribute('style', 'top:'+posY+"px;"+"left:"+posX+"px");
if(selectedText!="") ctx.children[0].innerHTML=selectedText;
}
else{
ctx.className="hidden";
customContextAction(e);
}
}

if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
customContextAction(e);
e.preventDefault();
}, false);
} else {
document.attachEvent('oncontextmenu', function(e){
customContextAction(e);
window.event.returnValue = false;
});
}
#context {
position: absolute;
width: 200px;
height: 150px;
background-color: #cacaca;
}
#context.hidden {
display: none;
}
#context .inner {}
Select something and right click anywhere!
<div id="context" class="hidden">
<div class="inner">
CONTEXT CONTENT
</div>
</div>

关于javascript - 如何在javascript中自定义右键单击选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27075406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com