mouseup事件后禁用jQuery contextMenu

Disabled jQuery contextMenu after a mouseup-event

本文关键字:jQuery contextMenu 事件 mouseup      更新时间:2023-09-26

在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。

RegEx搜索body标记和body标记中的所有HTML。上下文菜单的HTML是由body标记中的contextMenuJS添加的,因此它会被更改和中断。

我删除了getSelected和RegEx。我用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>