【问题标题】:Is there an easy way to allow an html document to scroll left and right?有没有一种简单的方法可以让 html 文档左右滚动?
【发布时间】:2022-02-17 02:01:08
【问题描述】:

我正在制作一个采用蜘蛛网样式设计的网页,这意味着内容会随着用户浏览而向左和向右移动。

我希望用户能够随意向左和向右滚动。

但是,我注意到在使用direction:ltr 时无法向左滚动。为了解决这个问题,我尝试在 html 上使用direction:rtl,在正文上使用direction:ltr。但是,当我这样做时,它变得无法向右滚动。可以选择在 html 上添加 margin-left: var(--left-content-width,0) 修饰符,但这会牺牲 Internet Explorer 11 的兼容性,并且使得跟踪视口左侧的所有内容变得更加困难。有没有一种简单的方法可以左右滚动(最好只使用 css,但 javascript 也不是不可能的),还是我们注定要永远不断地更新边距?

【问题讨论】:

    标签: html css scroll


    【解决方案1】:

    你可以使用这个:overflow-x: scroll;。如果有任何内容溢出屏幕,用户可以滚动查看。

    【讨论】:

    • 使用overflow: scroll 让用户向右滚动,左侧的内容保持隐藏
    • @Esdeseserdt1976 我认为我的回答有误。现在显示overflow-x: scroll;> 您可以查看overflow hereoverflow-x here 的文档。
    • 感谢您的努力,但我想我问的问题不够清楚。我将绝对定位的元素放置在视口的左侧,并尝试滚动到它们。我认为问题本身不是overflow/scroll 问题,而是内容似乎完全从 html 中省略了——例如,它不能以编程方式滚动到。
    【解决方案2】:

    为了方便遇到这个问题的人,这是我最后创建的拼凑解决方案。

    var button = document.getElementsByTagName("button")[0];
    var hiddenStyle = window.getComputedStyle(document.getElementById("hiddenContent"));
    var main = document.getElementsByTagName("main")[0];
    var mainStyle = window.getComputedStyle(main);
    button.onclick = showHidden;
    
    function showHidden() {
      main.style.marginLeft = hiddenStyle.getPropertyValue("right");
      window.scrollBy(parseInt(hiddenStyle.getPropertyValue("right")), 0);
    }
    div {
      background-color: green;
      width: 30%;
      height: 3em;
      right: 35%;
      left: 35%;
      top: calc(50% - 3em);
      position: absolute;
    }
    
    #hiddenContent {
      left: auto;
      right: 300vw;
      /*example, can be anything including calc() values*/
    }
    
    main {
      width: 100vw;
      height: 100vw;
      position: absolute;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <link rel="stylesheet" href="example.css">
    </head>
    
    <body>
      <main>
        <div id="firstContent">
          check this out- if you press
          <button>
              this button
             </button>, more content will appear
        </div>
        <div id="hiddenContent">
          this content is secret. Of course, there is a way for screen readers to see this but it's not needed in the minimum product
        </div>
      </main>
      <script href="example.js">
      </script>
    </body>
    
    </html>

    有点草率,但我希望这是一个很好的概念证明,可以帮助其他人不要像我那样花很长时间来解决类似的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多