javascript 手动触发DOM元素的滚动事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26252164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:43:04  来源:igfitidea点击:

Manually trigger a scroll event of DOM element?

javascriptjquery

提问by Nicolas S.Xu

I have two independent web elements, if I scroll the content of one element, I also want the 2nd element scroll at same time. Here is an example: https://stackedit.io

我有两个独立的网页元素,如果我滚动一个元素的内容,我也希望同时滚动第二个元素。这是一个例子:https: //stackedit.io

I did the following code, but it is not working:

我做了以下代码,但它不起作用:

element.find('.fullscreen-mk-content-textarea').on('scroll', function(e){
    // first element will trigger this event, then manully trigger the 
    // the scroll of the 2nd element. It's my plan. 
    console.log(e); // works
    element.find('.right-side').trigger('scroll'); // doesn't work...
});

What shall I do?

我该怎么办?

回答by Firanolfind

Vanilla Javascript

原生 JavaScript

var el = document.querySelector(".right-side");

el.dispatchEvent(new Event('scroll'));

回答by Romeo

Try this jsFiddle.

试试这个jsFiddle

$('.e1').scroll(function(e){
    $('.e2').scrollTop(parseInt($('.e1').scrollTop()));
});

回答by jfriend00

You can just set the scrollTopvalue of the other to match. That will cause it to scroll a desired amount. That's how you scroll something. It won't cause it to scroll by trying to trigger a scroll event. A scroll event is an indicator of some scroll motion, not something that causes scroll motion.

您可以只设置scrollTop另一个的值来匹配。这将导致它滚动所需的数量。这就是你滚动某些东西的方式。它不会通过尝试触发滚动事件导致它滚动。滚动事件是某种滚动运动的指示器,而不是导致滚动运动的东西。

If using jQuery, you can use .scrollTop()to retrieve the current value of the scroll or .scrollTop(val)to set the amount of scroll.

如果使用 jQuery,您可以使用.scrollTop()检索滚动的当前值或.scrollTop(val)设置滚动量。