focus() to input without scrolling

后端 未结 7 840
有刺的猬
有刺的猬 2020-12-08 18:03

I have a search input text which I\'d like to apply a focus() when loading the page, the problem is that the focus function automatically does a sc

相关标签:
7条回答
  • 2020-12-08 19:03

    The answers here do not take care of scrolling on the whole hierarchy, but the main scrollbars only. This answer will take care of everything:

        var focusWithoutScrolling = function (el) {
            var scrollHierarchy = [];
    
            var parent = el.parentNode;
            while (parent) {
                scrollHierarchy.push([parent, parent.scrollLeft, parent.scrollTop]);
                parent = parent.parentNode;
            }
    
            el.focus();
    
            scrollHierarchy.forEach(function (item) {
                var el = item[0];
    
                // Check first to avoid triggering unnecessary `scroll` events
    
                if (el.scrollLeft != item[1])
                    el.scrollLeft = item[1];
    
                if (el.scrollTop != item[2])
                    el.scrollTop = item[2];
            });
        };
    
    0 讨论(0)
提交回复
热议问题