使用滚动条滚动其他滚动条 [英] scroll other scrollbars with scrollbar
问题描述
我有3个带有滚动条的div. 如果我在div 1中滚动,我想在相反的方向滚动div 2和3. 滚动距离应为div 1距离的一半.
i have 3 divs with scrollbars. If i scroll in div 1 i want to scroll div 2 and 3 in the opposite direction. The distance scrolled should be half the distance of div 1.
这就是我现在所拥有的(一小部分,其余部分在jsfiddle中),适用于1格.
This is what i have now (small part, rest is in jsfiddle), which works for 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. 我尝试使用禁用代码来解决此问题,但这无济于事.
However, if i try to get the same for the other 2 divs then i can't scroll anything anymore. This is because div 1 triggers div 2 and div 2 triggers back to div 1 for example. I tried to fix this with the disable code but it doesn't help.
有人可以帮助我吗?
推荐答案
不要对@EmreErkan和@Simon的努力表示不敬.这是此版本的无点击版本.
No disrespect to @EmreErkan and @Simon for their effort. Here's a no-click version of this.
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());
});
}
这篇关于使用滚动条滚动其他滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!