如何在其他不可滚动的div上滚动滚动可滚动的div? [英] How to scroll a scrollable div when scrolled on other, non-scrollable div?

查看:76
本文介绍了如何在其他不可滚动的div上滚动滚动可滚动的div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题听起来令人困惑,但这就是我想要做的事情 - 在下面的片段中,如果用户在绿色div上滚动,我希望黄色div相应地滚动,就好像黄色div一样滚动了。

I know the question sounds confusing, but here is what I am trying to do - in the snippet below, if the user scrolls on the green div, I want the yellow div to be scrolled accordingly, just as if the yellow div was scrolled.

请注意,黄色div有 overflow:auto; 但是绿色div没有。

Note that the yellow div has overflow: auto; but the green one doesnt.

document.getElementById('green').addEventListener('wheel', function(e){

  console.log('scrolled!');

  console.log(e.deltaX); // it is always "-0"

  // scroll div#yellow accordingly

});

#yellow{
  background-color: yellow;
  display: inline-block;
  width: 200px;
  height: 200px;
  overflow: auto;
  vertical-align: top;
  padding 20px;
}

#green{
  background-color: green;
  display: inline-block;
  width: 100px;
  height: 200px;
  vertical-align: top;
}

<div id='yellow'>
  <p>1</p>
  <p>2</p>
  <p>3</p>
  <p>4</p>
  <p>5</p>
  <p>6</p>
  <p>7</p>
  <p>8</p>
  <p>9</p>
  <p>10</p>
</div>

<div id='green'></div>

我如何实现这一目标?

推荐答案

你是试图获取 deltaX 属性,垂直滚动所需的是 deltaY 一个。

You're trying to get the deltaX property, and what you need for vertical scrolling is the deltaY one.

document.getElementById('green').addEventListener('wheel', function(e){
  e.preventDefault();
  document.getElementById('yellow').scrollTop += e.deltaY * 10;
});

这篇关于如何在其他不可滚动的div上滚动滚动可滚动的div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆