我正在寻找一种解决方案,可以根据可信的html为选定的文本创建上下文菜单,以便创建链接。
工作流: 基本上用户可以从网页编辑文本(contenteditable =" true" div)如果他们想要添加指向所选文本的链接,他们必须使用上下文菜单,他们可以右键单击所选文本并从上下文菜单中输入框中键入URL,然后繁荣,所选文本将成为超链接。
欣赏你的方向。
答案 0 :(得分:4)
从here获取示例并从here更改一些演示,这是使用“contextmenu”事件的结果。现在您可以创建自己的功能。
if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
var pageX;
var pageY;
$(document).ready(function() {
$(document).on('contextmenu', function(ev) {
ev.preventDefault();
var selectedText = x.Selector.getSelected();
if(selectedText != ''){
$('ul.tools').css({
'left': pageX,
'top' : pageY - 20
}).fadeIn(200);
} else {
$('ul.tools').fadeOut(200);
}
});
$(document).on("click", function(e){
$('ul.tools').fadeOut(200);
});
$(document).on("mousedown", function(e){
pageX = e.pageX;
pageY = e.pageY;
});
});
body {
padding: 60px 10px;
}
ul.tools {
display: none;
list-style: none;
box-shadow: 0px 0px 4px rgba(0,0,0,.5);
border: solid 1px #000;
position: absolute;
background: #fff;
padding: 0;
}
ul.tools li {
height: 20px;
margin: 5px;
padding: 2px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true">Vestibulum vel orci hendrerit ligula pharetra volutpat et sed dui. Phasellus vitae feugiat dolor. Mauris eleifend neque ac iaculis aliquet. Nunc malesuada nisi in dictum tristique. Vestibulum mauris eros, varius sed faucibus sed, pellentesque et nunc. Curabitur ultricies blandit urna. Pellentesque ut augue mollis, lacinia dui non, rutrum justo. Nunc et odio dapibus, blandit leo eget, aliquet urna. Etiam lorem dolor, vehicula a purus in, fermentum congue diam. Integer vel urna nec turpis posuere tempor eu lacinia purus. Praesent mattis viverra lacus bibendum fringilla. Nulla commodo posuere ante, at cursus est rhoncus quis. In iaculis viverra neque in blandit. Pellentesque eleifend arcu diam, sed sodales ligula pharetra at. Morbi ac nisl adipiscing sem interdum convallis. </div>
<ul class="tools">
<li>Add link</li>
<li>Another item</li>
<li>Another item</li>
</ul>