jQuery focus without scroll

前端 未结 7 2239
时光取名叫无心
时光取名叫无心 2020-12-08 13:48

How can I focus to a HTML element (ex. \"a\") and do not change the current scroll settings.

For ex. if I use:

$(\'#link\').focus();
<
7条回答
  •  渐次进展
    2020-12-08 13:59

    I have the same problem, but in words: I think a more elegant solution would be to give the focus once the element is in the viewport.

    Here's what I copy/pasted (Kudos to ADB from this thread Jquery check if element is visible in viewport)

    $.fn.inView = function(){
        if(!this.length) return false;
        var rect = this.get(0).getBoundingClientRect();
    
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
    
    };
    
    
    
    window.$(window).on('scroll',function(){ 
    
        if( $('#elementcontainingfocus').inView() ) {
           $(function() {
                    $("#elementcontainingfocus input").focus();
                        $("input[type=text]:focus").css({  
                        "box-shadow": "0 0 5px rgba(81, 203, 238, 1)",
                        "border": "1px solid rgba(81, 203, 238, 1)"
                        });
                    });
        }
    
    });
    

提交回复
热议问题