If scrollbars are visible, scroll the content

时间:2015-07-28 16:00:34

标签: javascript html css user-interface user-experience

I have a fixed size div that dynamically shows content.

Should the content be too large for the div what I'd like to happen is for the contents of the div to start scrolling on it's own so the all the content can be seen.

Off the shelf solutions seem to force content to always scroll regardless if it fits inside in the div.

Thank you.

2 个答案:

答案 0 :(得分:1)

If you don't have css rules overriding your browser default styles, it's likely that scrollbars will appear automatically whenever there is overflowing content inside the element.

You can use javascript to test if the content overflows, and if it does, do whatever you want (add scrollbar, change style, use a jquery plugin for it etc...).

With jQuery:

var myDiv = $('#overflowing-div');
if (myDiv[0].scrollHeight > myDiv[0].clientHeight) {
    // handle this
}

Based on this answer to check if container is overflowing: How to detect overflow in div element?

答案 1 :(得分:1)

Adding to what Shahar mentioned, you can use jQuery animate api to scroll till the bottom of the div.

var dynamicDiv = $("#dynamic_div");
scrollHeight= dynamicDiv[0].scrollHeight;
divHeight = dynamicDiv.height();

if(scrollHeight > divHeight){
    pageScrolls = scrollHeight/divHeight;
    $("#dynamic_div").animate({
    scrollTop: scrollHeight // scroll till the end of the div
    }, 1500 * pageScrolls); // adjust the time based on how much scrolling needs to be done
}

Here's the jsfiddle