如何同时滚动两个div元素 [英] How to scroll two div elements at the same time
问题描述
我想同时滚动两个div,并且div在jquery ui对话框中. 我想检测其滚动事件,然后可以同时滚动它们.但第一步失败了. 对话框html是:
I want to scroll two div at the same time, and the divs are in a jquery ui dialog. I want to detect its scroll event, and then I could scroll them at the same time. but I fail at the first step. the dialog html is:
<div>
<div id="div1" style="width=3px; overflow-x:scroll;">hello, world ...</div>
<div id="div2" style="width=3px; overflow-x:scroll;">hello, world ...</div>
</div>
对话框js是:
$(ret).dialog({
width: 100,
height: 120
});
ret的内容是对话框html,我使用.ajax()来获取它.
the content of ret is the dialog html, and I get it by using .ajax().
滚动功能是:
$(document).on('scroll', 'div[id=1]', function() { alert("get it!"); }
不幸的是,滚动功能不起作用. 但是,如果我将滚动"更改为点击",它会起作用.我不知道为什么,你能帮我吗?谢谢!
unfortunately, the scroll function does not work. however, it works if I change 'scroll' to 'click'. I don't know why, could you help me? thank you!
$(document).on('click', 'div[id=1]', function() { alert("get it!"); }
推荐答案
您需要将滚动事件直接附加到滚动元素上,并使用scrollTop()
,scrollLeft()
获取位置值.这是一个简单的示例:
You need to attach the scroll event directly to the scrolled element and get the position values using: scrollTop()
, scrollLeft()
. Here is a quick example:
$(function(){
$("#dialog").dialog({
width: 400,
height: 400
});
$("#dialog div").on('scroll', function(e) {
var ele = $(e.currentTarget);
var left = ele.scrollLeft();
var top = ele.scrollTop();
if (ele.attr("id") === 'div1') {
$("#div2").scrollTop(top);
$("#div2").scrollLeft(left);
} else {
$("#div1").scrollTop(top);
$("#div1").scrollLeft(left);
}
});
});
这篇关于如何同时滚动两个div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!