简体   繁体   中英

Input focus using javascript

Is there a way to use javascript focus on an input without having the page scroll. I would like to have the curser start in the input field but I don't want it to scroll to that part of the page.

currently I am using

function setFocusToTextBox() {
    document.getElementById("FirstName1").focus();
}

You can get the scroll before then set the scroll after like this:

function setFocusToTextBox() {
    var doc = document.documentElement;
    var x = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
    var y = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
    document.getElementById("FirstName1").focus();
    window.scrollTo(x, y);
}

Code take from these links: link1 link2

You can get the scroll location before the focus then set it back to what it was right after you focus ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM