如何从鼠标右键单击的上下文菜单中捕获选择?

时间:2019-05-22 11:48:50

标签: javascript jquery contextmenu

如何从鼠标右键单击的上下文菜单中捕获选择?

尝试了contextmenu事件。但是右键单击就会触发它。

$("input").contextmenu(function(){
  console.log("test");
});

如何捕获从上下文菜单中选择的值?

2 个答案:

答案 0 :(得分:1)

使用e.target查找文本框值,如下所示:

$("input").val('This is sample text for selection . Select One or more word . You ay see selected result on console.');
$("input").contextmenu(function(e) {
  let selection = window.getSelection().toString();
  console.log($(e.target).val().replace($(e.target).val(), selection));
});
.clssize {
    width: 600px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' class='clssize' />

答案 1 :(得分:0)

尝试这个:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $("input").on('contextmenu', function(e) {
      alert($(this).val());
    });
  });
</script>