简体   繁体   English

如果元素不在Windows视图中,则滚动

[英]Scroll if element not in windows view

I have a table where you can select an element and then when ever you press the up or down arrow key the next or previous table row will be selected. 我有一个表格,您可以在其中选择一个元素,然后每当您按向上或向下箭头键时,就会选择下一个或上一个表格行。

for this purpose i have created the following jquery: 为此,我创建了以下jquery:

    $(document).keydown(function(e) {
    var ar=new Array(33,34,35,36,37,39);
    if(selected_row_id != null){
        var key = e.which;
        // up
        if(key == 38){
            $('#'+selected_row_id).prev().trigger('click');
            e.preventDefault();
        }
        //down
        if(key == 40 ){
            $('#'+selected_row_id).next().trigger('click');
            e.preventDefault();
        }

        if($.inArray(key,ar) > -1) {
            e.preventDefault();
            return false;
        }
        return true;
    }
});

This works fine however it has one mistake that annoys me. 这很好,但是有一个使我烦恼的错误。 When a table row is further down than you can actually see on the screen (meaning that you would have to scroll) the window doesnt scroll automaticly. 当表格行比您在屏幕上实际看到的位置靠下时(这意味着您必须滚动),窗口不会自动滚动。

My question is how is it possible to make sure that the window scrolls when an element is not visible on the screen? 我的问题是,当屏幕上看不到某个元素时,如何确保窗口滚动?

Here is a function taken from here : 这是从此处获取的函数:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
      && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
}

Returns true if the element is completely visible in the window, false otherwise. 如果元素在窗口中完全可见,则返回true ,否则返回false

If false is returned, then you can scroll your window appropriately. 如果返回false ,则可以适当滚动窗口。

Yes, this is possible. 是的,这是可能的。

Look at ScrollTo: http://www.w3schools.com/jsref/met_win_scrollto.asp 查看ScrollTo: http : //www.w3schools.com/jsref/met_win_scrollto.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM