我最后遇到的一个情况是,外部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/

最佳答案

试试这个:



 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;
        })

#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;
}

<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>

10-07 17:04