使用Javascript模拟滚动事件

发布于 2024-11-25 03:13:03 字数 487 浏览 4 评论 0原文

我正在尝试使用 Mobile Safari 的 Javascript 模拟滚动事件。 我使用以下代码

var evt = document.createEvent("MouseEvents");    
evt.initMouseEvent("scroll", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);

上面的代码是 jQuery 插件 jQuery.UI.Ipad 的一部分,它基本上映射触摸事件,如 touchstarttouchmovetouchend 到鼠标事件,如 mouseovermousedown

但是由于某些原因,模拟滚动事件的代码无法正常工作...请帮助我。所以本质上我的问题是如何模拟滚动事件。

I am trying to Simulate a scroll event using Javascript for Mobile Safari.
I am using the following code

var evt = document.createEvent("MouseEvents");    
evt.initMouseEvent("scroll", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);

The above code is part of a jQuery plugin jQuery.UI.Ipad which basically maps touch events like touchstart, touchmove, touchend to mouse events like mouseover, mousedown, etc

However for some reasons the code for simulating a scroll event is not working... Please help me. So essentially my question is how do I simulate the scroll event.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

素罗衫 2024-12-02 03:13:04

我认为人们对为什么要覆盖滚动控件感到困惑。我可以理解为什么你想模仿鼠标事件,但滚动也许不应该是其中之一。

通常对于滚动更改,您只需使用以下方法获取滚动:

var top = document.body.scrollTop;

并设置:

document.body.scrollLeft = sX;
document.body.scrollTop = sY;

I think people are confused as to why you would overide the scroll control. I can see why you want to imitate mouse events, but scroll maybe should not be one of them.

Usually for scroll changes you can just get the scroll with:

var top = document.body.scrollTop;

And set with:

document.body.scrollLeft = sX;
document.body.scrollTop = sY;
萌梦深 2024-12-02 03:13:04

所以,我知道我也需要模拟它。对我来说,当你有一个带有溢出框的灯箱时,你就会需要它。我能想到的众多案例中只有一个。寻找答案。只是想我会分享我所在的位置,你不是与 jQuery.Ui.Ipad 我会谷歌那个..但这是我到目前为止所得到的并且确实有效但并不完美。

    var inTouch=false;
    var timers_arr = new Array();
    var c=0;
    var t;
    var timer_is_on=0;
    //-------------------------------------------------------------------------------------------------------------------------------------------------------------
    // jeremy's timer functions
    //-------------------------------------------------------------------------------------------------------------------------------------------------------------
        function clearCount(timer){
                /// clear the time from timer
                clearTimeout(timers_arr[timer]);
                /// Make sure it's clear  
                timers_arr[''+timer+'']=0;
                delete timers_arr[''+timer+''];

        }
        function setCount(timer,time,func){
                clearCount(timer);
                if(timers_arr[timer]==0||typeof(timers_arr[timer]) === 'undefined'){
                  timers_arr[timer]=setTimeout(function(){
                                        func();                                                 
                        },time);
                }
        }

    function updatePos(evt,startY){
        setCount('touchmove',1,function(){
            var orig = evt.originalEvent;
            var curY = orig.changedTouches[0].pageY;
            var y = curY - startY;
            var sliderVal = $("#slider-vertical").slider("value");
            sliderVal += (y*.008);
            $("#slider-vertical").slider("value", sliderVal);
            updatePos(evt,startY);
        });
        setCount('touchmove_anitMotion',200,function(){
            clearCount('touchmove');
            clearCount('touchmove_anitMotion');
        });
    }
    var startX=0;
    var startY=0;
    var x=0;
    var y=0;
    var direction='';
    $('body').bind("onorientationchange", updateOrientation, false);
    $('#scroll-pane').live("touchstart", function(evt){
       inTouch=true;
       startX = event.targetTouches[0].pageX; 
       startY = event.targetTouches[0].pageY; 
    }); 
    $('#scroll-pane').live("touchmove", function(evt){
        evt.stopPropagation();
        evt.preventDefault();
        updatePos(evt,startY);
    }); 
    $('#scroll-pane').live("touchend", function(evt){
        startX=0;
        startY=0;
        clearCount('touchmove');
        inTouch=false;
    }); 
    $('#scroll-pane').live("touchcancel", function(evt){
        startX=0;
        startY=0;
        clearCount('touchmove');
        inTouch=false;
    });

再次不完美并希望修复它..但它至少有效。现在请注意,这是一个使用 jQuery UI 滑块作为滚动条的 div,如

http://jqueryui.com/demos/slider/#side-scroll

希望能激发一些想法。如果我得到一个超级稳定的答案,我会回来。
干杯-杰里米

So, I know I' need to simulate it too. for me it's when you have a lightbox with a overflow box that you would need it. Just one case of many I can think of. looking to for an answer. Just thought I'd share where I'm at, thou not with the jQuery.Ui.Ipad I will Google that.. but here is what I got so far and does work but not perfectly.

    var inTouch=false;
    var timers_arr = new Array();
    var c=0;
    var t;
    var timer_is_on=0;
    //-------------------------------------------------------------------------------------------------------------------------------------------------------------
    // jeremy's timer functions
    //-------------------------------------------------------------------------------------------------------------------------------------------------------------
        function clearCount(timer){
                /// clear the time from timer
                clearTimeout(timers_arr[timer]);
                /// Make sure it's clear  
                timers_arr[''+timer+'']=0;
                delete timers_arr[''+timer+''];

        }
        function setCount(timer,time,func){
                clearCount(timer);
                if(timers_arr[timer]==0||typeof(timers_arr[timer]) === 'undefined'){
                  timers_arr[timer]=setTimeout(function(){
                                        func();                                                 
                        },time);
                }
        }

    function updatePos(evt,startY){
        setCount('touchmove',1,function(){
            var orig = evt.originalEvent;
            var curY = orig.changedTouches[0].pageY;
            var y = curY - startY;
            var sliderVal = $("#slider-vertical").slider("value");
            sliderVal += (y*.008);
            $("#slider-vertical").slider("value", sliderVal);
            updatePos(evt,startY);
        });
        setCount('touchmove_anitMotion',200,function(){
            clearCount('touchmove');
            clearCount('touchmove_anitMotion');
        });
    }
    var startX=0;
    var startY=0;
    var x=0;
    var y=0;
    var direction='';
    $('body').bind("onorientationchange", updateOrientation, false);
    $('#scroll-pane').live("touchstart", function(evt){
       inTouch=true;
       startX = event.targetTouches[0].pageX; 
       startY = event.targetTouches[0].pageY; 
    }); 
    $('#scroll-pane').live("touchmove", function(evt){
        evt.stopPropagation();
        evt.preventDefault();
        updatePos(evt,startY);
    }); 
    $('#scroll-pane').live("touchend", function(evt){
        startX=0;
        startY=0;
        clearCount('touchmove');
        inTouch=false;
    }); 
    $('#scroll-pane').live("touchcancel", function(evt){
        startX=0;
        startY=0;
        clearCount('touchmove');
        inTouch=false;
    });

Again not perfect and looking to fix it.. but it's at the least working. Now note, this is a div that is using the jQuery UI slider for a scroll bar as (thou in mine it's vertical) shown in

http://jqueryui.com/demos/slider/#side-scroll

Hope that spurs some ideas. If I get a super stable answer I'll get back.
Cheers -Jeremy

等风来 2024-12-02 03:13:04

我需要这个来编写一个单元测试,为此我需要模拟滚动事件

function dispatchScroll(target,newScrollTop) {
      target.scrollTop = newScrollTop;
      var e = document.createEvent("UIEvents");
      // creates a scroll event that bubbles, can be cancelled,
      // and with its view and detail property initialized to window and 1,
      // respectively
      e.initUIEvent("scroll", true, true, window, 1);
      target.dispatchEvent(e);
    }

有关更多详细信息:

I needed this to write a unit test , for which i need to simulate a scroll event

function dispatchScroll(target,newScrollTop) {
      target.scrollTop = newScrollTop;
      var e = document.createEvent("UIEvents");
      // creates a scroll event that bubbles, can be cancelled,
      // and with its view and detail property initialized to window and 1,
      // respectively
      e.initUIEvent("scroll", true, true, window, 1);
      target.dispatchEvent(e);
    }

For more details : https://developer.mozilla.org/en-US/docs/Web/API/event.initUIEvent

陌伤浅笑 2024-12-02 03:13:04

对我有用的事件是鼠标滚轮,第 5 个参数需要为向下滚动为正,向上滚动为负。

var evt = document.createEvent("MouseEvents");    
evt.initMouseEvent("mousewheel", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);

请注意,FireFox 的事件类型为 DOMMouseScroll

The event that worked for me was mousewheel, and the 5th parameter needs to be positive for scrolldown and negative for scrollup.

var evt = document.createEvent("MouseEvents");    
evt.initMouseEvent("mousewheel", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);

Note that the event type is DOMMouseScroll for FireFox.

想你的星星会说话 2024-12-02 03:13:04

现在应该使用 CustomEvent 创建事件,例如 new CustomEvent("wheel", {detail: { deltaY: 1 } })document.createEvent 已弃用

https:// developer.mozilla.org/en-US/docs/Web/API/CustomEvent

我构建了这个实用程序函数,每帧滚动 1 个像素

const startFakeScrolling = (container: HTMLDivElement) => {
  const cb = () => {
    container.dispatchEvent(
      new CustomEvent("wheel", { detail: { deltaY: 1 } })
    );
    window.requestAnimationFrame(cb);
  };
  window.requestAnimationFrame(cb);
};

您还需要修改事件侦听器以使用详细信息,如 deltaY将是未定义的

const delta = e.deltaY != null ? e.deltaY : (e.detail as any).deltaY;

Events should now be created with CustomEvent as such new CustomEvent("wheel", { detail: { deltaY: 1 } }). document.createEvent is deprecated

https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent

I built this utility function that scrolls by 1 pixel every frame

const startFakeScrolling = (container: HTMLDivElement) => {
  const cb = () => {
    container.dispatchEvent(
      new CustomEvent("wheel", { detail: { deltaY: 1 } })
    );
    window.requestAnimationFrame(cb);
  };
  window.requestAnimationFrame(cb);
};

You will also need to modify the event listener to use detail, as deltaY will be undefined

const delta = e.deltaY != null ? e.deltaY : (e.detail as any).deltaY;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文