如何用鼠标滚轮水平滚动表格反应?

时间:2020-04-08 10:58:14

标签: javascript html css reactjs

我想使鼠标滚轮水平滚动表格。

我该怎么办?

CSS

table {
  border-collapse: collapse;
  border-spacing: 0;
  width: 100%;
  border: 1px solid #ddd;
}

th, td {
  text-align: left;
  padding: 8px;
}

.container {
  overflow-x: auto;
}


tr:nth-child(even){background-color: #f2f2f2}

逻辑代码:


function App() {
  const num = 50;
  let points_th = [];

  for(let i = 0; i < num; i++ ) {
    points_th.push(<th>Points</th>);
  }

  let row_1 = render_row('Jill', 'Smith', 50, num);
  let row_2 = render_row('Eva', 'Jackson', 94, num);
  let row_3 = render_row('Adam', 'Johnson', 67, num);
  return (
      <div>
        <div className='container'>
          <table>
            <tr>
              <th>First Name</th>
              <th>Last Name</th>
              {points_th}
            </tr>
              {row_1}
              {row_2}
              {row_3}
          </table>
        </div>
      </div>
  );
}

这是我的演示:https://codesandbox.io/s/github/Kalipts/scroll_table

1 个答案:

答案 0 :(得分:1)

使用onWheel event

当鼠标滚轮在元素上向上或向下滚动时,会发生onwheel事件。

使用Element.scrollTo()Element.scrollLeft

“元素”界面的scrollTo()方法滚动到给定元素内的一组特定坐标。

element.scrollTo({
  top: 100,
  left: 100,
  behavior: 'smooth'
});

代码示例:

const onWheel = e => {
  e.preventDefault();
  const container = document.getElementById("container");
  const containerScrollPosition = document.getElementById("container").scrollLeft;
  container.scrollTo({
    top: 0,
    left: containerScrollPosition + e.deltaY,
    behaviour: "smooth"
  });
};

<div className="container" id="container" onWheel={onWheel}>

enter image description here

引用:Horizontal Scrolling on React Component Using Vertical Mouse Wheel