Trigger 'dummy' mouse wheel event

2019-03-23 05:14发布

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

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

I need something like that just with an scrollwheel like:

$('#selector').trigger('DOMMouseScroll',{delta: -650});
//or mousewheel for other browsers

I can't do anything like 'fake it' with css trickery, I need to trigger the actual native (or as close as possible) event.

Thankyou!

9条回答
霸刀☆藐视天下
2楼-- · 2019-03-23 06:00

You can use the jquery scroll event and on call back u can do ur math. Please find the code snipet usefull.

//to make dummy paragraphs
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
//dummy paragraphs end here
//the below scroll() callback is triggered eachtime mouse wheel scroll happens
$( window ).scroll(function() { //i reference to window if u want u can iD a div and give div ID reference as well
  console.log("scolling....");
  //update with the delta u required.
});
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>scroll demo</title>
  <style>
  div {
    color: blue;
  }
  p {
    color: green;
  }
  span {
    color: red;
    display: none;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div>Try scrolling the iframe.</div>
<p>Paragraph - <span>Scroll happened!</span></p>
 

 
</body>
</html>

查看更多
看我几分像从前
3楼-- · 2019-03-23 06:04

You need to use jQuery.Event For example:

// Create a new jQuery.Event object with specified event properties.
var e = jQuery.Event( "DOMMouseScroll",{delta: -650} );

// trigger an artificial DOMMouseScroll event with delta -650
jQuery( "#selector" ).trigger( e );

Check more here: http://api.jquery.com/category/events/event-object/

查看更多
唯我独甜
4楼-- · 2019-03-23 06:05

Have you tried this? http://jquerytools.org/documentation/toolbox/mousewheel.html A plugin to "take control of the mousewheel" :)

查看更多
登录 后发表回答