jQuery focus without scroll

前端 未结 7 2201
时光取名叫无心
时光取名叫无心 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)"
                        });
                    });
        }
    
    });
    
    0 讨论(0)
  • 2020-12-08 13:59

    This worked for me

    var focusWithoutScrolling = function(element) {
        var fixed = { "position": "fixed" };
        var posStatic = { "position": "static" };
        $(":root").css(fixed);
        $("body").css(fixed);
        $("html").css(fixed);
        $(element).focus();
        $(":root").css(posStatic);
        $("body").css(posStatic);
        $("html").css(posStatic);
    }
    
    0 讨论(0)
  • 2020-12-08 14:10

    Try this:

    $.fn.focusWithoutScrolling = function(){
      var x = window.scrollX, y = window.scrollY;
      this.focus();
      window.scrollTo(x, y);
      return this; //chainability
    
    };
    

    and then

    $('#link').focusWithoutScrolling();
    

    Edit:

    It's been reported that this doesn't work in IE10. The probable solution would be to use:

    var x = $(document).scrollLeft(), y = $(document).scrollTop();
    

    but I haven't tested it.

    0 讨论(0)
  • 2020-12-08 14:11

    $('#link').css('position', 'fixed').focus().css('position', 'static') works in Firefox.

    (Edit: You should not use this hack)

    0 讨论(0)
  • 2020-12-08 14:18

    Try this jQuery solution:

    $('#link').select();
    
    0 讨论(0)
  • 2020-12-08 14:20

    Use {preventScroll: true} option on the focus method. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus

    If using jQuery try $('#el')[0].focus({preventScroll: true}) or iterate over each in your collection

    0 讨论(0)
提交回复
热议问题