最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Can a CSS overflow scrollbar be controlled in Javascript? - Stack Overflow

programmeradmin2浏览0评论

I have a div with a class overflow: 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.

I have a div with a class overflow: 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.

Share Improve this question edited May 16, 2011 at 20:16 Soatl 10.6k28 gold badges100 silver badges156 bronze badges asked May 16, 2011 at 19:58 StephenStephen 2,5503 gold badges34 silver badges60 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 7

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)

  1. 暂无评论