开发者

jQuery - If I'm moving a div with the keyboard

If I have a div wi开发者_运维百科th a fixed height and width, which I am moving using keypress (or keydown/keyup). Can I get the window to "follow" that div?

I know you can auto scroll a page, but can you get the co-ordinates of a div and scroll the page as the div moves?


are you using a javascript framework? If you use jQuery you can get the position of the div using:

jQuery('#yourdiv').position().top()
jQuery('#yourdiv').position().left()

Also, if you use jQuery, the window will automatically scroll to keep the Div in view anyway with no further work from you.

In response to your comment:

You can use jQuery('body').animate({scrollTop:xPosOfDiv});


One way:

$(document.body).bind('keydown', function(){
    $('#somediv')[0].scrollIntoView(true);
});

Another way:

$(document.body).bind('keydown', function(){
    $('#somediv').css('top', $(window).scrollTop() + 'px');
});

Smooth way:

$(document.body).bind('keydown', function(){
    $('#somediv').animate({'top': $(window).scrollTop() + 'px'}, 1000);
});


var pos = $("#theDiv").position();
window.scrollTo(pos.left, pos.top);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜