Possible to scroll caret into view inside a single HTML text field with JavaScript?

前端 未结 6 663
心在旅途
心在旅途 2021-02-04 03:41

Knowing the jQuery Caret plugin, I\'m still seeing no way to do the following on a single line text box in HTML (i.e. the input:type=text control) with JavaScript:<

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 03:50

    It's not possible to implement this behavior cross-browser. FireFox supports the KeyboardEvent.initKeyPress method, which allows key events to be simulated.

    See the comments at the function below for an explanation. I've successfully tested this function in FireFox 3.6.22, 7.0.1 and Chrome 14.

    The function itself is plugin-independent. Fiddle: http://jsfiddle.net/Jskbb/1/

    /* @name caretAtEnd
     * @description Places caret at the end
     * @param elem  DOM element
     * @param focus boolean, optional. If true, the element will be focused.
     */
    function caretAtEnd(elem, focus){
        var value = elem.value;
    
        //Add an extra character to the input field (necessary for this method)
        // An additional advantage is that the caret automatically moves to the end
        elem.value = elem.value + ".";
    
        try {
            // Create and simulate/trigger a [Backspace] keypress event.
            var evt = document.createEvent("KeyboardEvent");
            evt.initKeyEvent("keypress", 1, 1, null, 0, 0, 0, 0, 8, 0);
            elem.dispatchEvent(evt);
        } catch(e){
            //The current key event is not supported yet. Change back the value
            // In some browsers, the caret is at the end after executing this code.
            elem.value = value;
        }
    
        //Optionally, Focus on the element
        if(focus) elem.focus();
    }
    
    var element = $("#yourInputElement")[0]; //Important: Get the DOM element!
    caretAtEnd(element);
    

提交回复
热议问题