当外部div具有较小的宽度时,如何始终显示内部div的滚动条

时间:2017-05-10 15:47:31

标签: javascript html css scrollbar

我最终的结果是外部div具有一定的高度和宽度,而内部div具有一定的高度但是具有不确定的宽度。像这样:

HTML:

<div id="parent">
  <div id="child">
  </div>
</div

和css:

#parent{
  width: 200px;
  height: 200px;
  overflow-x:scroll; 
  overflow-y:hidden
}
#child{
  width: 400px;
  height: 200px;
  overflow-x:hidden;
  overflow-y:scroll;
}

但正如预期的那样,只有当它被滚动到最右边时,我才能看到内部div的滚动条。

我想要始终显示两个滚动条。

请帮我找一个CSS解决方案或普通的js(非jquery)解决方案。

https://jsfiddle.net/n2tfe2wr/

1 个答案:

答案 0 :(得分:2)

试试这个:

&#13;
&#13;
 document.getElementById('child-size').style.width = document.getElementById('child-wrapper').scrollWidth+ 'px';
        document.getElementById('parent').addEventListener('scroll', function () {
            document.getElementById('child-wrapper').style.marginLeft = document.getElementById('parent').scrollLeft + 'px';
            document.getElementById('child-wrapper').scrollLeft = document.getElementById('parent').scrollLeft;
        })
&#13;
#parent {
    width: 200px;
    height: 400px;
    overflow-x: scroll;
    overflow-y: hidden;
    position: relative;
}

#child-wrapper {
    width: 200px;
    height: 200px;
    overflow-x: hidden;
    overflow-y: scroll;
    background-color: blue;
}

#child {
    width: 400px;
    color: white;
}

#child-size {
    height: 1px;
    opacity: 0;
}
&#13;
<div id="parent">
    <div id="child-size"></div>
    <div id="child-wrapper">
        <div id="child">
            Lorem ipsum ad his scripta blandit partiendo, eum fastidii accumsan euripidis in, eum liber hendrerit an.
            <br><br><br>
            Qui ut wisi vocibus suscipiantur, quo dicit ridens inciderint id. Quo mundi lobortis reformidans eu,
            legimus senserit definiebas an eos.

            <br><br><br>
            Eu sit tincidunt incorrupte definitionem, vis mutat affert percipit cu,
            eirmod consectetuer signiferumque eu per.
            <br><br><br>
            In usu latvine equidem dolores.
            <br><br><br>
            Quo no falli viris intellegam, ut fugit veritus placerat per.
        </div>
    </div>

    <br><br>
    Lorem ipsum ad his scripta blandit partiendo, eum fastidii accumsan euripidis in, eum liber hendrerit an.
    <br><br><br>
    Qui ut wisi vocibus suscipiantur, quo dicit ridens inciderint id. Quo mundi lobortis reformidans eu,
    legimus senserit definiebas an eos.

    <br><br><br>
    Eu sit tincidunt incorrupte definitionem, vis mutat affert percipit cu,
    eirmod consectetuer signiferumque eu per.
    <br><br><br>
    In usu latvine equidem dolores.
    <br><br><br>
    Quo no falli viris intellegam, ut fugit veritus placerat per.
</div>
&#13;
&#13;
&#13;