admin管理员组

文章数量:1336631

Here's what I'm trying to make. I want a div which appears as a box of fixed dimensions, into which various javascript functions will be placing text over time. When the number of lines of text exceeds the height of the box, I'd like a scrollbar to appear alongside the box, so that you can scroll through the text inside it while the box itself remains a fixed height.

How could this be acplished?

Here's what I'm trying to make. I want a div which appears as a box of fixed dimensions, into which various javascript functions will be placing text over time. When the number of lines of text exceeds the height of the box, I'd like a scrollbar to appear alongside the box, so that you can scroll through the text inside it while the box itself remains a fixed height.

How could this be acplished?

Share Improve this question asked May 13, 2012 at 19:18 temporary_user_nametemporary_user_name 37.1k48 gold badges160 silver badges243 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

using css you can do this:

div{
   overflow-y: scroll
}

you can also overflow-y: auto as @tw16

As you say the scrollbar should only appear when there is too much text, I would use:

div{
    overflow-y: auto
}

Live example: http://jsfiddle/RMpFu/

Use overflow in CSS:

document.querySelector("div").style.overflowY = "scroll";  //For Y
document.querySelector("div").style.overflowX = "scroll";  //For X

document.querySelector("div").style.overflow = "scroll";   //For both ;)

P.S.

If you want it to show the scroll bar only when necessary, you can do this instead:

document.querySelector("div").style.overflow = "auto";    //JavaScript

//-or-

div{
    overflow: auto;                       /*CSS*/
}
<script type="text/javascript">
$(function() { 
   $('.holeEvent').hover(function() {
      $(this).removeClass('holeEvent').addClass('holeEvent2');
   },
   function(){
      $(this).removeClass('holeEvent2').addClass('holeEvent');
   });
});
</script>
<style type="text/css">
.holeEvent {
   height: 50px;
   overflow-y: hidden;
}
.holeEvent2 {
   height: 50px;
   overflow-y: scroll;
}
</style>

<div class="holeEvent2"></div>

本文标签: javascriptHow to make a scrollbar appearStack Overflow