开发者

Can a CSS overflow scrollbar be controlled in Javascript?

I have a div with a class ov开发者_如何学JAVAerflow: auto; Is there a way to control this scrollbar when it appears?

I have a ajax photo gallery (no page refresh) where some caption text is in a div, but the content is of varying length. If you scroll down in this div and then advance to the next slide, the scrollbar does not go back to the top. So, I was wondering if there was a way to control this scrollbar. Thanks.


With jQuery, you can set the top of the scroll area like so:

$('#contents').scrollTop(0);

Here's a demo showing this in action->

Note that this is also possible without jQuery:

document.getElementById('contents').scrollTop = 0;

And a demo of that->

For both demos, press the Reset button to set the scroll bar back to the top.


You can change the value of the property scrollTop of the <div> element.

See element.scrollTop on MDC docs

See element.scrollTop on MSDN

While scrollTop is not part of any standard, it is supported by all major browsers.


To move the vertical bar back to the top on an overflowed element myControl , you must do

$("#myControl").scrollTop(0);

or, in case of horizontal bar, to move it to the beginning (left)

$("#myControl").scrollLeft(0);

If you want to hide the scroll bars, you must do this CSS

#myControl {
    overflow: hidden;
}

You are assuming that the next slide resides on the top. If you have absolute positionated slides, you might better do the following, to ensure that you scroll to the correct nextSlide location:

var nextSlidePos = $("#slide" + nextSlide).position();
$("#myControl").scrollTop( nextSlidePos.top ).scrollLeft( nextSlidePos.left );


Update after a test, using elm.scrollTop = 0:

<div style="overflow:auto;height:100px;width:100px">
    <p>test</p>
    <p>test</p>
    <p>test</p>
    <a href="javascript:" onclick="this.parentNode.scrollTop = 0">go up</a>
</div>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜