简体   繁体   中英

How to set x and y scroll position on a div with overflow: scroll?

If I have the following markup:-

 .outerDiv { width: 500px; overflow: scroll; }.innerDiv { width: 1000px; }
 <div class="outerDiv"> <div class="innerDiv"> </div> </div>

How do I (most likely with JavaScript) set the x and y position of that scroll?

You can use scrollLeft and scrollTop properties. Ex:

document.getElementById("yourScrollElementId").scrollTop = 100

Or you can use jquery methods to make it easier and animated as well.

You can use jQuery scrollLeft() and scrollTop() methods.

$('.outerDiv').scrollLeft(300);
$('.outerDiv').scrollTop(50);

Example: https://jsfiddle.net/upwrrj70/

A working example:

 document.getElementById('mySection').scrollTop = 50
 section { border: 1px solid gray; overflow-y: scroll; max-height: 50px; }
 <section id="mySection"> <div>foo 1</div> <div>foo 2</div> <div>foo 3</div> <div>foo 4</div> <div>foo 5</div> <div>foo 6</div> <div>foo 7</div> <div>foo 8</div> <div>foo 9</div> </section>

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