Scroll page on text input focus for mobile devices?

前端 未结 3 533
自闭症患者
自闭症患者 2021-02-02 15:01

Im making a mobile optimised site with a text input which filters a list as you type. Its similar to this: http://jquerymobile.com/test/docs/lists/lists-search.html

For

相关标签:
3条回答
  • 2021-02-02 15:25

    Agreed - that'd be nice for usability.

    If you're using jQuery, this should do the trick:

    $('#id-of-text-input').on('focus', function() {
        document.body.scrollTop = $(this).offset().top;
    });
    
    0 讨论(0)
  • 2021-02-02 15:39

    A better solution would be:

    $('#id-of-text-input').on('focus', function() {
       document.body.scrollTop += this.getBoundingClientRect().top - 10
    });
    

    Because offsetTop (or .offset().top if using Jquery) returns the distance from the first positioned parent, whereas you need the distance from the top of the document.

    getBoundingClientRect().top returns the distance between the current viewport position to the element, u.e. if you're scrolled 300px below the element, it would return -300. So adding the distance using += would scroll to the element. -10 is optional - to allow some space at the top.

    0 讨论(0)
  • 2021-02-02 15:42
    $('input, textarea').focus(function () {
        $('html, body').animate({ scrollTop: ($('input, textarea').offset().top - 10) }, 1);
        return false;
    });
    
    0 讨论(0)
提交回复
热议问题