How to scroll two div elements at the same time

2019-01-26 17:11发布

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>

the dialog js is:

$(ret).dialog({
    width: 100,
    height: 120
});

the content of ret is the dialog html, and I get it by using .ajax().

the scroll function is:

$(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!"); }

标签: jquery scroll
1条回答
【Aperson】
2楼-- · 2019-01-26 17:45

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:

JSnippet Demo

$(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);
        }
    });
});
查看更多
登录 后发表回答