So DOM scrollIntoView aligns top/bottom, but what about left/right?

后端 未结 2 589
无人共我
无人共我 2021-01-07 22:21

I would like to scroll horizontally the given element. The only way I find is using ScrollIntoView DOM method, which allows either align the element\'s bottom with the view

2条回答
  •  礼貌的吻别
    2021-01-07 23:03

    I've recently had a problem with a table header that had inputs as filters for each column. Tabbing through the filters would move the focus, but if one of the inputs wasn't visible or if it was partly visible, it would only JUST bring the input into view, and I was asked to bring the full input and column into view. And then I was asked to do the same if tabbing backwards to the left.

    This link helped to get me started: http://www.webdeveloper.com/forum/showthread.php?197612-scrollIntoView-horizontal

    The short answer is that you want to use:

    document.getElementById('myElement').scrollLeft = 50;
    

    or:

    $('#myElement')[0].scrollLeft = 50;
    

    Here's my solution (which may be overkill for this question, but maybe it'll help someone):

    // I used $.on() because the table was re-created every time the data was refreshed
    // #tableWrapper is the div that limits the size of the viewable table
    // don't ask me why I had to move the head head AND the body, they were in 2 different tables & divs, I didn't make the page
    
    $('#someParentDiv').on('focus', '#tableWrapper input', function () {
        var tableWidth = $('#tableWrapper')[0].offsetWidth;
        var cellOffset = $(this).parent()[0].offsetLeft;
        var cellWidth = $(this).parent()[0].offsetWidth;
        var cellTotalOffset = cellOffset + cellWidth;
    
            // if cell is cut off on the right
        if (cellTotalOffset > tableWidth) {
            var difference = cellTotalOffset - tableWidth;
            $('#tableWrapper').find('.dataTables_scrollHead')[0].scrollLeft = difference;
            $('#tableWrapper').find('.dataTables_scrollBody')[0].scrollLeft = difference;
        }
            // if cell is cut off on the left
        else if ($('#tableWrapper').find('.dataTables_scrollHead')[0].scrollLeft > cellOffset) { 
            $('#tableWrapper').find('.dataTables_scrollHead')[0].scrollLeft = cellOffset;
            $('#tableWrapper').find('.dataTables_scrollBody')[0].scrollLeft = cellOffset;
        }
    });
    

提交回复
热议问题