开发者

How to Scroll a webpage by clicking and Dragging on the Body like touch Device

开发者 https://www.devze.com 2023-02-05 10:25 出处:网络
Is it possible to scroll a website by holding mouse button down and Dragging开发者_StackOverflow中文版 vertically or horizontally on the body ( like touch devices ipad). Is there any way to implement

Is it possible to scroll a website by holding mouse button down and Dragging开发者_StackOverflow中文版 vertically or horizontally on the body ( like touch devices ipad). Is there any way to implement this please guide me.

Thank You


You could try overscroll plugin.

And here you can find more examples...


I came across this method, courtesy of this codepen (It's pure JS, but has some flaws)

I've rewritten it with JQuery and edited it to fix the browser issues (Scroll distances retrieved from document not body), and included a preventDefault as this fixes an issue where the dragging occasionally continued after the mouse is released.

var curYPos = 0;
var curXPos = 0;
var curDown = false;

$(document).on("mousemove", function (event) {
  if (curDown === true) {
    $(document).scrollTop(parseInt($(document).scrollTop() + (curYPos - event.pageY)));
    $(document).scrollLeft(parseInt($(document).scrollLeft() + (curXPos - event.pageX)));
  }
});

$(document).on("mousedown", function (e) { curDown = true; curYPos = e.pageY; curXPos = e.pageX; e.preventDefault(); });
$(window).on("mouseup", function (e) { curDown = false; });
$(window).on("mouseout", function (e) { curDown = false; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://picsum.photos/id/10/1000/800" />

Pure JS original (Quite broken, but included for reference):

var curYPos = 0,
  curXPos = 0,
  curDown = false;

window.addEventListener('mousemove', function(e) {
  if (curDown === true) {
    window.scrollTo(document.body.scrollLeft + (curXPos - e.pageX), document.body.scrollTop + (curYPos - e.pageY));
  }
});

window.addEventListener('mousedown', function(e) {
  curDown = true;
  curYPos = e.pageY;
  curXPos = e.pageX;
});
window.addEventListener('mouseup', function(e) {
  curDown = false;
});
<img src="https://picsum.photos/id/10/1000/800" />

0

精彩评论

暂无评论...
验证码 换一张
取 消