简体   繁体   中英

focus scrollable div to a position

I have got a table in a div like below:

<div class="posts" style="height: 800px; width:330px; overflow:scroll;" >
         <table class="price" id="price" cellpadding="10px" border="1">
                // some stuff    

         </table>
</div>

I want to focus the div to scroll to a particular row of the table by using Javascript or jQuery. So, the user will see that row in the middle of the div block if the function is called.

How can I do this? Thanks!

Basically, you get a reference to the cell( <td> ) or row ( <tr> ) you'd like to scroll to. Then, you just call the scrollIntoView method of that element.

Ie

var tgtElement = document.getElementById('idOfDesiredRowOrCell');
tgtElement.scrollIntoView();

Here's a quick example, note that I simply locate the desired row by number - you'd most likely wish to choose your target element differently. Also, note that there are 20 rows created, therefore the range of valid input is [0..19] - Choosing 19 will scroll until row 19 is visible - though it is at the bottom of the div, rather than the top. I imagine you could add some <br> elements after the table if you really had to scroll the selected line to be at the top of the div.

HTML:

<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}

window.addEventListener('load', mInit, false);

function mInit()
{
    var tbl = makeTable(20, 5);
    byId('scrollMe').appendChild(tbl);

    byId('doScrollBtn').addEventListener('click', onScrollBtnClick, false);
}

function onScrollBtnClick()
{
    var tbl = byId('demoTable');
    var rowNum = byId('scrollRowInput').value;
    var selectedRow = tbl.rows[rowNum];
    selectedRow.scrollIntoView();
}

function makeTable(numRows, numCols)
{
    var x, y, tbl, row, cell;
    tbl = newEl('table');
    tbl.id = 'demoTable';
    for (y=0; y<numRows; y++)
    {
        row = newEl('tr');
        for (x=0; x<numCols; x++)
        {
            cell = newEl('td');
            cell.appendChild( newTxt("Cell: " + x + ", " + y) );
            row.appendChild(cell);
        }
        tbl.appendChild(row);
    }
    return tbl;
}

</script>
<style>
#scrollMe
{
    height: 150px;
    border: solid 1px red;
    overflow-y: scroll;
}
</style>
</head>
<body>
    <div id='scrollMe'></div>
    <input id='scrollRowInput'/><button id='doScrollBtn'><-- Scroll to this row</button>
</body>
</html>

maybe jQuery scrollTop can help you achieve that. Please check the code below, at the end you'll find the link to a working example:

JavaScript

$(document).ready(function(){
    // Count rows
    var length = $('tr', $('.price')).not('tr:first').length;
    // Build links to rows from row 1 (to ignore table header)
    for( i=1; i <= length; i++ ) {
        $('.pages').append('<a class="linkrow" href="'+i+'">Row '+i+'</a> | ');
    }
    // On click
    $('a.linkrow').on('click',function(e){
        // Prevent default
        e.preventDefault();
        // Get row index from link href
        var rowId = $(this).attr('href');
        // Get row position by index
        var ypos = $('.price tr:eq('+rowId+')').offset().top;
        // Go to row
        $('.posts').animate({
            scrollTop: $('.posts').scrollTop()+ypos
        }, 500);
        // Some CSS to visualize which row is being viewed
        $('.price tr').css({'background-color': 'none'});
        $('.price tr:eq('+rowId+')').css({ 'background-color': '#ccc' } );
    });
});

jsFiddle example: http://jsfiddle.net/laelitenetwork/XEfHr/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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