Trigger 'dummy' mouse wheel event

前端 未结 9 915
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 22:30

Is there a way to trigger a scroll wheel event with an arbitrary delta. Just like jQuery does with \'click\' like:

$(\'#selector\').trigger(\'click\');
         


        
9条回答
  •  被撕碎了的回忆
    2021-01-03 22:56

    You can try typing this into the console, and see its effects:

    document.body.scrollTop = document.body.scrollTop + 200
    

    where 200 is an arbitrary number. Similarly, you can also try this with scrollLeft:

    document.body.scrollLeft = document.body.scrollLeft + 200
    

    or

    document.body.scrollLeft = document.body.scrollLeft - 200
    

    You could try playing with this concept and the window setInterval() method.

    Additionally........

    You can get the offset of an element as follows:

    jQuery("#vote-to-add-section").offset()
    

    which will give you a result like:

    {top: 9037.1875, left: 268}
    

    You could scroll to that element with something like this:

    document.body.scrollTop = jQuery("#vote-to-add-section").offset().top
    

    Alternatively........

    If you just want the site to already be scrolled down to a particular element when the site is first loaded, you can do this with elements that have an id:

    Add #idnamehere to the end of a url you are seaching. There must be an element with that id name on the page.

    For example compare these URL's, and what you get when you enter them in the URL address bar:

    https://travel.usnews.com/rankings/worlds-best-vacations https://travel.usnews.com/rankings/worlds-best-vacations/#vote-to-add-section

    The one with #vote-to-add-section at the end is automatically scrolled down to the element with id #vote-to-add-section.

提交回复
热议问题