Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

jquery - How to scroll two div elements at the same time

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!"); }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...