使用滚动条滚动其他滚动条

我有3个带滚动条的div。 如果我在div 1中滚动,我想在相反的方向上滚动div 2和3。 滚动的距离应该是div 1距离的一半。

这就是我现在拥有的(小部分,rest在jsfiddle),适用于1 div。

$("#textBox1").scroll(function () { console.log("scroll 1"); var offset = $("#textBox1").scrollTop() - scrollPosTBox1; var half_offset = offset/2.0; disable1 = true; if(disable2 == false) { $("#textBox2").scrollTop(scrollPosTBox2 - half_offset); } if(disable3 == false) { $("#textBox3").scrollTop(scrollPosTBox3 - half_offset); } disable1 = false; }); 

但是,如果我尝试为其他2个div进行相同的操作,那么我就不能再滚动任何东西了。 这是因为div 1触发div 2,div 2触发返回div 1。 我尝试使用禁用代码修复此问题,但它没有帮助。

有人能帮我吗?

http://jsfiddle.net/XmYh5/1/

不要对@EmreErkan和@Simon的努力不尊重。 这是一个无需点击的版本。

 var $boxes = $("#textBox1,#textBox2,#textBox3"), active; $boxes.scrollTop(150); // set initial scrollTop values updateScrollPos(); // bind mouseenter: // 1) find which panel is active // 2) update scrollTop values $boxes.mouseenter(function () { active = this.id; updateScrollPos(); }); // bind scroll for all boxes $boxes.scroll(function (e) { $this = $(this); // check to see if we are dealing with the active box // if true then set scrolltop of other boxes relative to the active box if(this.id == active){ var $others = $boxes.not($this), offset = $this.scrollTop()-$this.data("scroll"), half_offset = offset / 2; $others.each(function(){ $this = $(this); $this.scrollTop($this.data("scroll") - half_offset); }); } }); // utility function: // assign scrollTop values element's data attributes (data-scroll) function updateScrollPos() { $boxes.each(function(){ $this = $(this); $this.data("scroll",$this.scrollTop()); }); } 

小提琴

您可以使用变量来确定带有.mousedown()活动文本框,并在它处于活动状态时执行该操作;

 var activeScroll = ''; $("#textBox1").on('mousedown focus mouseenter', function () { activeScroll = 'scroll1'; }).scroll(function () { if (activeScroll == 'scroll1') { console.log("scroll 1"); var offset = $("#textBox1").scrollTop() - scrollPosTBox1; var half_offset = offset / 2.0; $("#textBox2").scrollTop(scrollPosTBox2 - half_offset); $("#textBox3").scrollTop(scrollPosTBox3 - half_offset); } }); 

您可以在此处查看更新的jsFiddle 。

终于得到了一个动态的解决方案,比我想象的更复杂,但我想我得到了它:

http://jsfiddle.net/XmYh5/14/

 var initialTop = 150, factor = 2; $(".textBox") .addClass('disabled') .scrollTop(initialTop) .on('scroll', function () { var $this = $(this); if(!$this.is('.disabled')) { this.lastOffset = this.lastOffset || initialTop; var offset = $this.scrollTop(), step = (offset - this.lastOffset) / factor; $this.siblings().each( function() { var $this = $(this), offset = $this.scrollTop() - step; $this.scrollTop(offset); this.lastOffset = offset; }); this.lastOffset = offset; } }) .on('mouseenter', function() { $(this).removeClass('disabled').siblings().addClass('disabled'); });