Get current cursor position in a textbox

后端 未结 2 1761
生来不讨喜
生来不讨喜 2020-11-29 06:28

I need a code to find current position of cursor in a textbox/textarea. It should work with chrome and firefox. Following is the code which I am using:

2条回答
  •  猫巷女王i
    2020-11-29 07:00

    It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

    function textbox()
    {
            var ctl = document.getElementById('Javascript_example');
            var startPos = ctl.selectionStart;
            var endPos = ctl.selectionEnd;
            alert(startPos + ", " + endPos);
    }

    Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

提交回复
热议问题