内置了一个滚动控制器,需要反转它

Built a scroll controller, need to reverse it

本文关键字:控制器 滚动 一个 内置      更新时间:2023-09-26

我的代码允许在底部垂直滚动以控制顶部的水平滚动。

我的杰斯菲德尔

您将看到颜色在渐变中移动。效果很好。问题是我似乎无法完全让相反的工作。在顶部水平滚动控件在底部滚动。

有什么想法吗?

以下是使其工作的脚本:

// Add event listener for scrolling
$("#bottom").on("scroll", function bottomScroll() {
    var scrolledleft = parseInt($("#bottom").scrollTop()) * 1;
    console.log(scrolledleft + scrolledright)
    $("#top").scrollLeft(scrolledleft + scrolledright)
})
//Move right column to bottom initially
$("#top").scrollLeft($("#top").height())
//Get actual distance scrolled
var scrolledright = parseInt($("#top").scrollLeft())

事件处理程序需要暂时相互取消,以便它们不会同时触发。 您想根据当前 scrollLeft/(子div 的宽度 - 容器的宽度)计算您的位置百分比,然后将该百分比应用于其他元素,同样适用于顶部/高度。 此外,我在 CSS 中将 #top 的高度更改为 50%。

var handler = function (e) {
  var src = e.target;
  
  // the first element that triggers this function becomes the active one, until it's done
  if (!activeScroller) activeScroller = src.id;
  else if (activeScroller != src.id) return;
  
  var $b = $("#bottom");
  var $t = $("#top");
  var scrollH = $("#bottom-content").height() - $b.height();
  var scrollW = $("#top-content").width() - $t.width();
  var scrollPct = 0;
  if (src.id == "top") {
    if (scrollW > 0) {
      scrollPct = $t.scrollLeft() / scrollW;
    }
    $b.scrollTop(scrollH * scrollPct);
  } else {
    if (scrollH > 0) {
      scrollPct = $b.scrollTop() / scrollH;
    }
    $t.scrollLeft(scrollW * scrollPct);
  }
  
  // give all animations a chance to finish
  setTimeout(function () { activeScroller = ""; }, 100);
};
var activeScroller = "";
$("#top,#bottom").on("scroll", handler);
#top {
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  left: 0;
  width: 100%;
  height: 50%;
  position: fixed;
  overflow: auto;
  background: red;
}
#top-content {
  height: 100%;
  width: 2000px;
  background: linear-gradient(90deg, red, blue);
}
#bottom {
  position: absolute;
  margin: auto;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50%;
  position: fixed;
  overflow: auto;
  background: green;
  z-index: 100;
}
#bottom-content {
  height: 2000px;
  width: 100%;
  background: linear-gradient(0deg, orange, green);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="top">
  <div id="top-content"></div>
</div>
<div id="bottom">
    <div id="bottom-content"></div>
</div>

看看这个:https://jsfiddle.net/1p7gp72h/1/

我不确定你在这里的最终目标是什么。

$("#top").on("scroll", function topScroll() {
    var scrolledleft = parseInt($("#top").scrollTop()) * 1;
    $("#bottom").scrollLeft(scrolledleft + scrolledright)
});
#top {
  top: 0;
  right: 0;
  left: 0;
  width: 5000px;
  height: 100%;
  overflow: auto;
  background: red;
  overflow-x: scroll;
  overflow-y: hidden;
  white-space:nowrap;
}

向左滚动 ::

$('div').scrollLeft(1000);
滚动

回正常/向右滚动 ::

$('div.slick-viewport').scrollLeft(-1000);