在 jQuery 中使用自定义文本选择函数时,我的 contextMenu 事件被禁用。
最小的工作示例,带有 javascript 和 html 文件(javascript 的数量比看起来要少):
var markFeature = {
getSelected: function(){
var t = '';
if(window.getSelection)
t = window.getSelection();
else if(document.getSelection)
t = document.getSelection();
else if(document.selection)
t = document.selection.creatRange().text;
return t;
},
applyHighlight: function(){
var st = markFeature.getSelected();
if(st!='')
{
var str1 = '<span style="background-color:#00E000">';
var replacement = str1.concat(st,"</span>");
var _st = new RegExp(st, "g");
var replaced = $("body").html().replace(_st, replacement);
$("body").html(replaced);
}
},
register_contextMenu: function(){
//markFeature.addCSS();
$.contextMenu({
selector: '*',
items: {
"item1": {name: "item-1"},
"item2": {name:"item-2"},
}
});
},
init: function(){
$(document).bind("mouseup", markFeature.applyHighlight);
}
};
$(document).ready(markFeature.register_contextMenu);
$(document).ready(markFeature.init);
<link href="http://medialize.github.io/jQuery-contextMenu/src/jquery.contextMenu.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://medialize.github.io/jQuery-contextMenu/src/jquery.contextMenu.js"></script>
<strong>Right-Click ME!</strong>
请忽略一个小错误:有时它会在选择后添加文本。
所以我的问题是:选择后我无法使用 contextMenu。
最佳答案
正则表达式搜索 body 标记以及 body 标记内的所有 HTML。上下文菜单的 HTML 由 contextMenu JS 添加到 body 标记内,因此它会被更改和中断。
我删除了 getSelected
和正则表达式。我用改编的 example 替换了它们来自Rangy :
<script src="http://rangy.googlecode.com/svn/trunk/currentrelease/rangy-core.js"></script>
<script src="http://rangy.googlecode.com/svn/trunk/currentrelease/rangy-cssclassapplier.js"></script>
<style type="text/css">
.highLight {
background-color: #00E000;
}
</style>
<script>
var cssApplier, markFeature;
window.onload = function() {
rangy.init();
cssApplier = rangy.createCssClassApplier("highLight", {
normalize: true
});
};
$(this).on("mouseup", function() {
cssApplier.applyToSelection();
});
markFeature = {
register_contextMenu: function() {
$.contextMenu({
selector: "*",
items: {
item1: {
name: "item-1"
},
item2: {
name: "item-2"
}
}
});
},
init: function() {
$(document).bind("mouseup", markFeature.applyHighlight);
}
};
$(document).ready(markFeature.register_contextMenu);
$(document).ready(markFeature.init);
</script>
关于javascript - mouseup 事件后禁用 jQuery contextMenu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26806498/