如何创建一个“循环滚动内容”的“水平滚动条”(允许无限向右/向左滚动)?

问题描述 投票:0回答:1

编程/代码新手 - 在这里,在寻找/创建正确的代码方面遇到了一些困难! 任何帮助将不胜感激!

首先,这是我的 CSS 和 HTML 代码:

CSS:

.LoopingScroll{
  overflow-x: auto;
  white-space: nowrap;
  max-width: 200px;
}

HTML 是:

<!doctype html>
<html>
 <head>
  <title>LoopingScroll</title>
  <link rel="stylesheet"
   href="style.css">
 </head>

 <body>

<table class="table"> 

    <thead>
        <tr> 
      <th>TestingA</th> 
      <th>TestingB</th>
      <th>TestingC</th>
    </tr> 
    </thead> 

  <tbody>   
      <tr class="active"> 
      <td>TestingD</td> 
      <td>TestingE</td>
      <td class="LoopingScroll"> 
        Testing01 Testing02
        Testing03 Testing04
        Testing05 Testing06
        Testing07 Testing08
      </td> 
    </tr> 
     </tbody> 

</table> 

  <script src="script.js">
  </script>
 </body>
</html>

现在,这就是我所拥有的: “我有一个水平滚动条,显示“Testing01”到“Testing08”。”这很棒。 但这就是我想要的: **“作为人们,我希望使用水平滚动条从“Testing01 到Testing08”。 我希望他们滚动栏内容再次循环,这样“人们可以继续向右滚动,它不断从测试 01 循环到测试 08,在测试 08 测试 01 后,再次测试 08。所以人们永远不会必须“向左滚动”**(除非他们愿意。如果他们“向左滚动,那就太棒了,他们也可以无休止地向左滚动,但这不是现在的主要优先事项。”)

我正在努力解决的主要问题是:“有谁知道/有关于我应该用于循环其内容的水平滚动条的代码的建议吗?”

谢谢!

-Scholah

html css scrollbar horizontal-scrolling
1个回答
0
投票

这是一个使用 JavaScript 的解决方案:

document.addEventListener("DOMContentLoaded", function() {
  const scrollElement = document.querySelector('.LoopingScroll');
  let originalContent = scrollElement.innerHTML;
  let contentToAdd = originalContent;

  scrollElement.addEventListener('scroll', function() {
    let atRightEnd = (scrollElement.scrollWidth - scrollElement.scrollLeft - scrollElement.clientWidth) < 50;

    if (atRightEnd) {
      scrollElement.innerHTML += contentToAdd;
    }
  });
});
.LoopingScroll {
  overflow-x: auto;
  white-space: nowrap;
  max-width: 200px;
}
<table class="table">
  <thead>
    <tr>
      <th>TestingA</th>
      <th>TestingB</th>
      <th>TestingC</th>
    </tr>
  </thead>
  <tbody>
    <tr class="active">
      <td>TestingD</td>
      <td>TestingE</td>
      <td class="LoopingScroll">
        Testing01 Testing02 Testing03 Testing04 Testing05 Testing06 Testing07 Testing08
      </td>
    </tr>
  </tbody>
</table>

© www.soinside.com 2019 - 2024. All rights reserved.