0

我有一个项目,其中有一个溢出的单杠。在开头和结尾有移动溢出位置的按钮。此时,用户必须单击按钮才能移动溢出。

我不想创建当悬停在它们上方时不断移动溢出直到到达终点或用户从按钮上移开鼠标时的按钮。编码

我试图将“oclick”更改为“onmouseover”并使函数异步。然后添加第二个“onmouseout”功能。但我一直在不断循环,网络应用程序中断。

let isHovered = false;

async function scollTopBar(direction) {
      var parent = document.getElementById("parent");
      isHovered = true;
      let amount = 1;
      while(isHovered){
         if (direction === "left") amount *= -1;
         parent.scrollLeft += amount;
         setTimeout(() => {}, 100);
      }
}

function mouseRemoved() {
      isHovered = false;
}

我没有包含上面的代码,以免破坏浏览器。

var parent = document.getElementById("parent")


function scollTopBar(direction) {
      var parent = document.getElementById("parent");
      let amount = 20;
      if (direction === "left") amount *= -1;
      parent.scrollLeft += amount;
}
.cotainer {
  width: 30rem;
  height: 3rem;
  display: flex;
  background-color: red;
}

p{
  margin: 0;
  padding: 0;
  white-space: nowrap;
}

button {
  height: 100%;
}

.parent {
  height: 100%;
  display: flex;
  align-items: center;
  overflow: auto;
}

.child {
  padding: 0 1rem;
  border-right: 1px solid blue;
  background-color: green;
  
  display: inline-flex;
}
<div class="cotainer">
  <button onclick="scollTopBar('left')">b</button>
  <div class="parent" id="parent">
    <div class="child">
      <p>Hello</p>
      <p>Hello</p>
    </div>
    <div class="child">
      <p>Hello World</p>
      <p>Hello</p>
    </div>
    <div class="child">
      <p>Hello WorldHelloWorld</p>
      <p>Hello</p>
    </div>
    <div class="child">
      <p>World</p>
      <p>Hello</p>
    </div>
    <div class="child">
      <p>Hello WorldHello World</p>
      <p>Hello</p>
    </div>
    <div class="child">
      <p>Hello</p>
    </div>
    <div class="child">
      <p>HelloWorld</p>
      <p>Hello</p>
    </div>
    <div class="child">
      <p>HelloWorld</p>
      <p>Hello</p>
    </div>
  </div>
  <button onclick="scollTopBar('right')">n</button>
</div>

4

1 回答 1

1

在 vanilla JS 中,你应该有这样的东西,左右是按钮 --->

let left = document.getElementById("left");
  let right = document.getElementById("right");

  left.onmouseover = () => {
    scrollTopBar(-20);
  };
  right.onmouseover = () => {
    scrollTopBar(20);
  };

  function scrollTopBar(direction) {
    var parent = document.getElementById("parent");

    let int = setInterval(() => {
      parent.scrollLeft += direction;
    }, 100);

    left.onmouseout = () => {
      clearInterval(int);
    };
    right.onmouseout = () => {
      clearInterval(int);
    };
  }
于 2021-02-02T14:18:09.713 回答