jQuery: move window viewport to show freshly toggled element

回眸只為那壹抹淺笑 提交于 2019-12-03 07:20:42

问题


I have a snippet of jQuery in doc ready which toggles a div containing a 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 
});

The toggle works fine when clicking the link. The problem I'm having is that if div#addnote-area is below the browser's current viewport, it remains there when it's shown. I'd like the user's cursor to go to the textarea and for the whole textarea to be viewable in the window.


回答1:


Check out the scrollTo jQuery plugin. You can simply do something like this:

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

Or, if you want to animate it, provide the # of milliseconds for the scrolling to last:

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



回答2:


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)




回答3:


jQuery's scrollTop also works. Try setting like:

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

You can get height/width pretty easily using $(...).offset().



来源:https://stackoverflow.com/questions/2329281/jquery-move-window-viewport-to-show-freshly-toggled-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!