15

我在 doc ready 中有一段 jQuery 片段,它可以切换包含一个 div textarea

$('div#addnote-area').hide(); // hide the div
$('a#addnote-link').click(function() { // click event listener on link
     $('div#addnote-area').toggle(); // toggle the hidden div 
});

单击链接时切换工作正常。我遇到的问题是,如果div#addnote-area它低于浏览器的当前视口,它会在显示时保留在那里。我希望用户的光标转到 textarea 并让整个 textarea 在窗口中可见。

点击这里查看图片

4

3 回答 3

54

Without the scrollTo plugin

$(window).scrollTop($('div#addnote-area').offset().top)

EDIT: Well I sure get a lot of points from this old answer :)

Here's a bonus, this can also be animated.

Just use the animate() function and target the body tag:

$('body').animate({scrollTop:$('div#addnote-area').offset().top},500)

Try it on Stackoverflow! Open the inspector console and run

$('body').animate({scrollTop:$('#footer').offset().top},500)

于 2010-05-13T23:21:16.853 回答
4

查看scrollTo jQuery 插件。你可以简单地做这样的事情:

$.scrollTo('div#addnote-area');

或者,如果您想对其进行动画处理,请提供滚动持续的毫秒数:

$.scrollTo('div#addnote-area', 500);
于 2010-02-24T20:35:06.173 回答
1

jQueryscrollTop也可以。尝试设置如下:

 $('#idOfElement').css('scrollTop', 10)

你可以很容易地使用$(...).offset().

于 2010-05-13T23:15:45.893 回答