问题
I have seen and used jQuery for synchronized scrolling, but for my current project am forced to find an Angular solution wherever possible. Unfortunately, I am not having any luck finding the "Angular way" for this problem.
Put simply, I need my top div (table header) to scroll horizontally in sync with my bottom div (table body). The two divs are children of a wrapper div. The first child is the slave, the second is the master, but I'm not sure what goes into the function to link the slave position to the master position...
.directive('scroll', [function() {
return {
link: function(scope, element, attrs) {
ch = elem.children();
slave = ch[0];
master= ch[1];
slave.bind('scroll', function(event){
...
});
};
}]);
回答1:
Here is my example. It was initially written to combine vertical scrolls for two elements with the same size which are positioned in different blocks on page. I've rewritten it for horizontal scroll.
But it needs elements to be the same width. And it synchronizes the scroll - they are both master and slave at one time. If your elements have different sizes, you can set scroll using a proportion, something like el.scrollLeft = scrollLeft*(el.width/otherEl.width)
.
回答2:
My example (needs https://github.com/jquery/jquery-mousewheel):
myApp.directive("scrollGroup", function () {
return function(scope, element, attrs) {
element.bind("mousewheel", function(e) {
e.preventDefault();
$("[scroll-group='" + attrs.scrollGroup + "']").each(function () {
$(this).scrollTop($(this).scrollTop() - e.deltaY);
$(this).scrollLeft($(this).scrollLeft() + e.deltaX);
});
});
};
});
You can then do something like:
<div class='div1' scroll-group='scroll_grp1'></div>
<div class='div2' scroll-group='scroll_grp1'></div>
<div class='div3' scroll-group='scroll_grp1'></div>
...
Does even work, when css overflow: hidden
is set for the divs. That was important, because I did not want to see scrollbars in all the divs.
Tested in Firefox and Chrome and Safari 8.
来源:https://stackoverflow.com/questions/24296881/how-do-i-synchronize-the-scroll-position-of-two-divs-using-angularjs