如何将滚动条附加到div部分?

时间:2013-11-04 06:33:57

标签: javascript jquery html css

我刚刚写了一个带有几个div-s和一点CSS和javascript的页面。 我不知道如何将滚动条插入我的div之一。 代码并不难理解。 CSS和javascript包含在代码中。

<html>
<head>
<style>
#container 
{
    vertical-align: top;
    width: 98%;
    height: 90%;
    padding: 5px;
}
#discussion {
    width: 99%;
    height: 90%;
    overflow-y: scroll;
    border: 1px solid #ccc;
    padding: 5px;
    text-align: left;
    /*position: absolute; bottom: 0; left: 0;*/
    position: relative;
}
#content
{
    overflow-y: auto;
    position: absolute; bottom: 0; left: 0;
}
#message {
    width: 100%;
    vertical-align:bottom;
    padding: 5px;
    border: 1px solid #ccc;
}
</style>
<script>
function init(){
    var message = $('#message');
    var content = $('#content');
    message.keypress(function (e) {
        if (e.keyCode == 13 && message.val().length > 0) {
            content.append(message.val() + "<br/>");
            //content.scrollTop(discussion.get(0).scrollHeight); //works fine with top to down
            message.val('').focus();
        }
    });
};
</script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body onload="javascript:init();">
     <div id="container">
        <div id="discussion">
            <div id="content"></div>
        </div>
        <input id="message" type="text" placeholder="Hit Enter button to insert"/> 
     </div>
</body>
</html>

当内容退出讨论部分时,我需要滚动条。 事情是当我从上到下插入一些文本流动滚动条工作正常。 很遗憾,所有文字都必须从下到上插入。

---------------
-
-
-
-
- first text
---------------


---------------
-
-
-
- first text
- second text
---------------


---------------
- second text
- third text
- fourth text
- fifth text
- sixth text
--------------- now I need a scroll bar to see first text.

3 个答案:

答案 0 :(得分:0)

您将高度设置为90%,但它不知道90%的高度。 如果您希望将其设置为正文的90%,则需要设置html,body {height: 100%;}

然后你需要删除你对内容的绝对定位。

在这里工作小提琴:http://jsfiddle.net/davidpauljunior/2PpqN/

答案 1 :(得分:0)

问题的主要原因是您错过了设置 #content div的宽度和高度。

所以加上

width: 100%;
height: 100%;

对于父元素 discussion ,而不是使用%值粘贴height的静态值,以便用户可以查看它。目前查看滚动条非常小。

width: 100%;
height: 200px;

JSFiddle

希望你明白。

答案 2 :(得分:0)

您需要从#discussion移除溢出,并在#content

中将位置更改为亲戚

CSS

#discussion {
    width: 99%;
    height: 90%;

    border: 1px solid #ccc;
    padding: 5px;
    text-align: left;
    /*position: absolute; bottom: 0; left: 0;*/
    position: relative;
}
#content
{
    overflow: auto;
    position: relative;
    height:100px;
    width:100%;
}

更新fiddle

相关问题