Detect direction of user selection with javascript

后端 未结 5 1082
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 05:43

I am emulating text editor in my project with custom caret, but native selection. Is there any way how to detect in which direction did user select the text? Lets say, that

5条回答
  •  滥情空心
    2020-12-30 06:11

    track the mousedown X offet and then the mouseup X offset, and the result shows the direction: (using jQuery)

    var textSelectionDirection = (function(){
        var direction = '', mouseDownOffset = null;
    
        function getDirection(e){
            if( e.type == 'mousedown' )
                mouseDownOffset = e.clientX;
            else if( e.type == 'mouseup' ){
                direction = e.clientX < mouseDownOffset ? 'left' : 'right';
                console.log(direction);
            }
        }
    
        return getDirection
    })();
    
    $(document).on('mousedown mouseup', textSelectionDirection);
    

    DEMO: http://jsfiddle.net/ffumv/

提交回复
热议问题