如何处理源自鼠标点击而非键盘操作的光标活动?

时间:2016-10-27 11:03:55

标签: javascript codemirror

当用户通过鼠标点击将光标移动到另一个位置时,我想做某事,但是当通过键盘操作(箭头,pageup / pagedown,home / end)完成时,我不想这样做。

  • 我不能只听cursorActivity,因为它会触发键盘和鼠标操作。
  • 我不确定我是否可以听mousedown,因为它可能是某些不是光标位置变化的开始(例如选择,拖动)。

捕捉那些由鼠标引起的光标移动的最佳方法是什么?

3 个答案:

答案 0 :(得分:6)

你可以听这些事件:

  • 鼠标按下
  • cursorActivity
  • KEYDOWN
  • beforeChange

如果满足以下条件,则通过鼠标单击移动光标:

  • cursorActivity事件
  • 后触发mousedown事件
  • 两个事件之间没有按下任何移动键
  • 两个事件之间的内容没有变化
  • 未选择任何文字



var movedByMouse = false;

var editor = CodeMirror(document.body);

editor.on("mousedown", function () {
    movedByMouse = true;
});

editor.on("cursorActivity", function () {
    if (movedByMouse) {
        movedByMouse = false;
        if (!editor.getSelection()) {
            console.log("Moved by mouse");
        }
    }
});

editor.on("keydown", function () {
    if (isMovementKey(event.which)) {
        movedByMouse = false;
    }
});

editor.on("beforeChange", function () {
    movedByMouse = false;
});

function isMovementKey(keyCode) {
    return 33 <= keyCode && keyCode <= 40;
};
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.20.2/codemirror.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.20.2/codemirror.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:4)

所有鼠标事件(我知道):

  • 的onclick
  • oncontextmenu
  • ondbclick
  • onmousedown事件
  • OnMouseEnter在
  • OnMouseLeave在
  • 的OnMouseMove
  • 的onmouseover
  • 的onmouseout
  • onmouseup

所以,基本上,在javascript AFAIK中,你的问题没有解决办法。但是,您可以使用第二个建议并跟踪事件,并根据它们选择是否执行您的操作。

&#13;
&#13;
var editorElement = document.body;
var codeMirror = CodeMirror(editorElement);
var mouseEvents = [
  'click',
  'contextmenu',
  'dbclick',
  'mousedown',
  'mouseenter',
  'mouseleave',
  'mousemove',
  'mouseover',
  'mouseout',
  'mouseup'
];
var mouseEventsLog = [];
var lastCursorPosition = null;
var doAction = function() {
  var previousEvent = mouseEventsLog[mouseEventsLog.length - 2];
  var lastEvent = mouseEventsLog[mouseEventsLog.length - 1];

  if (((previousEvent === 'mousedown' && lastEvent === 'mouseup') || lastEvent === 'click') &&codeMirror.getSelection().length <= 0) {
    if (codeMirror.getCursor() !== lastCursorPosition) {
      console.log('Cursor changed by clicking.');
    }
  }

  lastCursorPosition = codeMirror.getCursor();
};
for (var i = 0; i < mouseEvents.length; i++) {
  editorElement.addEventListener(mouseEvents[i], function(event) {
    mouseEventsLog.push(event.type);
    if (event.type == 'mouseup') {
      doAction();
    }
  }, false);
}
&#13;
<script src="https://codemirror.net/lib/codemirror.js"></script>
<script src="http://codemirror.net/mode/javascript/javascript.js"></script>
<link href="https://codemirror.net/lib/codemirror.css" rel="stylesheet"/>
&#13;
&#13;
&#13;

注意:我尝试合并cursorActivity和鼠标事件,但cursorActivity在它们之前执行?我实际上不确定那里发生了什么= D

答案 2 :(得分:3)

您可以使用钩子挂钩到CodeMirror,并定义自己的事件,当光标从编辑器上单击鼠标变化时触发该事件

CodeMirror.defineInitHook(function (editor) {
    editor.cursorDidChange = false;
    $(editor.getWrapperElement()).on({
        mousedown : function() {
            if (editor.cursorDidChange) CodeMirror.signal(editor, 'cursorClick');
        },
        mouseup : function() {
            editor.cursorDidChange = false;
        }
    });
    editor.on('cursorActivity', function(e) {
        if (e.isSelection) editor.cursorDidChange = true;
    });
    editor.on('beforeSelectionChange', function(e, range) {
        var start = range.ranges[0].anchor, end = range.ranges[0].head;
        e.isSelection = range.origin == '*mouse' && start.line == end.line && start.ch == end.ch;
    })
});

这使用一个标志和一个计时器来捕获两个事件,如果它们在彼此的短时间内发生,因为点击处理程序在cursorActivity处理程序之后立即触发。

以下是如何将新定义的事件与CodeMirror一起使用的工作示例:

/* Create Hook */
CodeMirror.defineInitHook(function (editor) {
	editor.cursorDidChange = false;
	$(editor.getWrapperElement()).on({
    	mousedown : function() {
            if (editor.cursorDidChange) CodeMirror.signal(editor, 'cursorClick');
        },
        mouseup : function() {
            editor.cursorDidChange = false;
        }
    });
    editor.on('cursorActivity', function(e) {
    	if (e.isSelection) editor.cursorDidChange = true;
    });
    editor.on('beforeSelectionChange', function(e, range) {
        var start = range.ranges[0].anchor, end = range.ranges[0].head;
        e.isSelection = range.origin == '*mouse' && start.line == end.line && start.ch == end.ch;
    })
});
/* -------------- */
/* Create an editor to test it */

var $this = $('.code').eq(0),
    $code = $this.html(),
    $unescaped = $('<div/>').html($code).text();
        
$this.empty();
    
var editor = CodeMirror($this.get(0), {
    value       : $unescaped,
    mode        : 'javascript',
    lineNumbers : true,
    readOnly    : false
});

/* Lets test out the new event */
editor.on('cursorClick', function() {
	$('<div />', {text : 'Cursor moved when clicked !'}).appendTo('#result')
        .show(1).delay(1000).fadeOut(function() {
         	$(this).remove();
        });
});
body {background: #eee;}
.code {margin: 10px 0;}
#result {color: green;}
.CodeMirror {height: auto!important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://codemirror.net/lib/codemirror.js"></script>
<script src="https://codemirror.net/mode/javascript/javascript.js"></script>
<link href="https://codemirror.net/lib/codemirror.css" rel="stylesheet"/>
<!-- EDITOR -->
<div class="code">test.fn = test.prototype = {
    display : function() {}
        console.log("Move cursor by clicking");
        console.log("Move cursor with keys");
    },
	pushStack: function( elems ) {
		// This is just pseudocode to have something to test
	}
    return false;
}</div>
<!-- EDITOR END -->
<div id="result"></div>