jQuery focus without scroll

前端 未结 7 2228
时光取名叫无心
时光取名叫无心 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 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.

提交回复
热议问题