如何获取文本区域中所选单词的行和列?

时间:2018-05-11 07:08:21

标签: javascript html selection

我有一个用户可以输入文本的文本区域。当他们选择文本时,如果他们没有选择任何文本,我想获取所选文本(或光标)的行和列。

以下示例使用on focus事件。它应该使用游标更改或选择更改事件。

    static async Task TestApiAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:33854/");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var result = await client.PostAsync("api/School", "hello", new JsonMediaTypeFormatter());

            result.EnsureSuccessStatusCode();

            // if it something returns
            string resultString = await result.Content.ReadAsAsync<string>();
            Console.WriteLine(resultString);
        }
    }
document.getElementById('textarea').onselectionchange = onFocusHandler;
document.getElementById('textarea').onselect = onFocusHandler;
document.getElementById('textarea').onfocus = onFocusHandler;
document.getElementById('textarea').onmouseup = onFocusHandler;
document.getElementById('textarea').onselectionstart = onFocusHandler;

function onFocusHandler(event){
    var textarea = document.getElementById('textarea');
    var value = textarea.value;
    var anchorPosition = 0;
    var activePosition = 0;
    var userSelection;
    var range;
    console.log(event.type);
    
    if (window.getSelection) {
        //console.log("1");
        userSelection = window.getSelection();
        //console.log(userSelection);
        //range = userSelection.getRangeAt(0);
        //console.log(range);
    }
    else if (document.selection) {
        userSelection = document.selection.createRange();
    }
    
    console.log("Cursor:" + userSelection.anchorOffset);
    return;

    if (userSelection.getRangeAt) {
        //range = userSelection.getRangeAt(0);
    }
    else {
        range = document.createRange();
        range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
        range.setEnd(userSelection.focusNode, userSelection.focusOffset);
    }
    
    //console.log(range);
    
    textarea.focus();
    
    if (textarea.setSelectionRange) {
       textarea.setSelectionRange(anchorPosition, activePosition);
    }
    else {
       var range = textarea.createTextRange();
       range.collapse(true);
       range.moveEnd('character', activePosition);
       range.moveStart('character', anchorPosition);
       range.select();
    }
};

0 个答案:

没有答案