search

Home  >  Q&A  >  body text

javascript - 如何在input聚焦时自动滚动到该input的位置?

当我点击教务处账号那个input时,我希望是这样的;

但实际上却是这样的

我写了一段js试图解决这个问题:

$("input").on("focus",function(){
    var pos = $(this).position().top;
    $(window).scrollTop(pos);
})

昨天测的时候是有用的,pos值大概有100~200,但是今天测的时候只有13。

请问各位是怎么处理这种问题的?还有上述代码错在哪?

阿神阿神2901 days ago452

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-10 14:54:56

    感谢 依云,问题已解决

    $("input").on("focus",function(){
        this.scrollIntoView();
    })
    

    reply
    0
  • 怪我咯

    怪我咯2017-04-10 14:54:56

    input元素是否嵌套在其它元素内?如果是则需要计算父元素的偏移量+input偏移量。

    reply
    0
  • Cancelreply