css 使用jQuery拖动时滚动页面

k75qkfdt  于 2023-03-05  发布在  jQuery
关注(0)|答案(9)|浏览(146)

我试过使用kinetic.js和下面的代码,但是当我在IE11中尝试这个时,它总是在我每次滚动时跳到顶部:

$("html").kinetic();

我想让页面在平板电脑、IE10和IE11上可以滚动,这样用户就可以像在移动的设备上一样向上推页面向下滚动。
如何在pure-JS或jQuery中做到这一点,而不跳到顶部?

zwghvu4y

zwghvu4y1#

你可以通过记录鼠标点击时的位置和拖动鼠标时的当前位置来实现这一点。

var clicked = false, clickY;
$(document).on({
    'mousemove': function(e) {
        clicked && updateScrollPos(e);
    },
    'mousedown': function(e) {
        clicked = true;
        clickY = e.pageY;
    },
    'mouseup': function() {
        clicked = false;
        $('html').css('cursor', 'auto');
    }
});

var updateScrollPos = function(e) {
    $('html').css('cursor', 'row-resize');
    $(window).scrollTop($(window).scrollTop() + (clickY - e.pageY));
}

要防止拖动时选择文本,请添加以下CSS:

body {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

Example fiddle

    • 更新**

下面是一个jQuery插件版本,扩展后可以通过设置进行垂直和水平滚动,还可以更改cursor
一个一个二个一个一个一个三个一个一个一个一个一个四个一个

zbq4xfa0

zbq4xfa02#

我只是想补充一下,用Rory的代码我做了水平滚动。

var clicked = false, base = 0;

$('#someDiv').on({
    mousemove: function(e) {
        clicked && function(xAxis) {
            var _this = $(this);
            if(base > xAxis) {
                base = xAxis;
                _this.css('margin-left', '-=1px');
            }
            if(base < xAxis) {
                base = xAxis;
                _this.css('margin-left', '+=1px');
            }
        }.call($(this), e.pageX);
    },
    mousedown: function(e) {
        clicked = true;
        base = e.pageX;
    },
    mouseup: function(e) {
        clicked = false;
        base = 0;
    }
});
ngynwnxp

ngynwnxp3#

这段代码将工作在水平和垂直鼠标拖动滚动。这是相当简单。

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; });
j1dl9f46

j1dl9f464#

基于Rory McCrossan的思想,用AngularJS2. 0实现。

import {Directive, ElementRef, OnDestroy, Input} from "@angular/core";

declare var jQuery: any;

@Directive({
    selector: '[appDragScroll]'
})
export class DragScrollDirective implements OnDestroy {

    @Input() scrollVertical: boolean = true;
    @Input() scrollHorizontal: boolean = true;

    private dragging = false;
    private originalMousePositionX: number;
    private originalMousePositionY: number;
    private originalScrollLeft: number;
    private originalScrollTop: number;

    constructor(private nodeRef: ElementRef) {
        let self = this;

        jQuery(document).on({
            "mousemove": function (e) {
                self.dragging && self.updateScrollPos(e);
            },
            "mousedown": function (e) {
                self.originalMousePositionX = e.pageX;
                self.originalMousePositionY = e.pageY;
                self.originalScrollLeft = jQuery(self.nodeRef.nativeElement).scrollLeft();
                self.originalScrollTop = jQuery(self.nodeRef.nativeElement).scrollTop();
                self.dragging = true;
            },
            "mouseup": function (e) {
                jQuery('html').css('cursor', 'auto');
                self.dragging = false;
            }
        });

    }

    ngOnDestroy(): void {
        jQuery(document).off("mousemove");
        jQuery(document).off("mousedown");
        jQuery(document).off("mouseup");
    }

    private updateScrollPos(e) {
        jQuery('html').css('cursor', this.getCursor());

        let $el = jQuery(this.nodeRef.nativeElement);
        if (this.scrollHorizontal) {
            $el.scrollLeft(this.originalScrollLeft + (this.originalMousePositionX - e.pageX));
        }
        if (this.scrollVertical) {
            $el.scrollTop(this.originalScrollTop + (this.originalMousePositionY - e.pageY));
        }
    }

    private getCursor() {
        if (this.scrollVertical && this.scrollHorizontal) return 'move';
        if (this.scrollVertical) return 'row-resize';
        if (this.scrollHorizontal) return 'col-resize';
    }

}
qeeaahzv

qeeaahzv5#

根据第一个答案,这是鼠标拖动时水平滚动的代码:

var clicked = false, clickX;
$(document).on({
    'mousemove': function(e) {
        clicked && updateScrollPos(e);
    },
    'mousedown': function(e) {
        e.preventDefault();        
        clicked = true;
        clickX = e.pageX;
    },
    'mouseup': function() {
        clicked = false;
        $('html').css('cursor', 'auto');
    }
});

var updateScrollPos = function(e) {
    $('html').css('cursor', 'grabbing');
    $(window).scrollLeft($(window).scrollLeft() + (clickX - e.pageX));
}
lnxxn5zx

lnxxn5zx6#

我修改了Rory的代码很多,我得到了每个元素侧滚动的工作。我需要一个项目,有多个滚动磁贴在一个网页应用程序的单一视图。添加.drag类到任何元素,可能做一些样式,它应该很好去。

// jQuery sidescroll code. Can easily be modified for vertical scrolling as well.
// This code was hacked together so clean it up if you use it in prod.
// Written by Josh Moore
// Thanks to Rory McCrossan for a good starting point

// How far away the mouse should move on a drag before interrupting click
// events (your own code must also interrupt regular click events with a
// method that calls getAllowClick())
const THRESHOLD = 32;
var clicked = false;
var allowClick = true;

// mouseX: most recent mouse position. updates when mouse moves.
//     el: jQuery element that will be scrolled.
//    thX: "threshold X", where the mouse was at the beginning of the drag
var mouseX, startY, el, thX;

// Add the .drag class to any element that should be scrollable.
// You may need to also add these CSS rules:
//   overflow: hidden; /* can be replaced with overflow-x or overflow-y */
//   whitespace: none;
function drag() {
    $('.drag').on({
        'mousemove': e => {
            if (el != null && clicked) {
                el.scrollLeft(el.scrollLeft() + (mouseX - e.pageX));
                mouseX = e.pageX;
                allowClick = Math.abs(thX - mouseX) > THRESHOLD ? false : true;
            }
        },
        'mousedown': e => {
            clicked = true;
            // This lets the user click child elements of the scrollable.
            // Without it, you must click the .drag element directly to be able to scroll.
            el = $(e.target).closest('.drag');
            mouseX = e.pageX;
            thX = e.pageX;
        },
        'mouseup': e => {
            clicked = false;
            el = null;
            allowClick = true;
        }
    });
}

function getAllowClick() {
    return allowClick;
}

同样,我没有使用垂直滚动,但它将是相当简单的添加(取代X的Y的,scrollTop()取代scrollLeft(),等等)。希望这有助于有人在未来!

zvokhttg

zvokhttg7#

这个框架是用vanilla javascript编写的,最适合我。
它还支持divs中的滚动条。
注意:如果创建动态内容,请在渲染后调用dragscroll.reset();
dragscroll
用途
demo

kmb7vmvb

kmb7vmvb8#

下面是一个基于单个元素类的简单滚动解决方案

var cursordown = false;
      var cursorypos = 0;
      var cursorxpos = 0;
      $('.cursorgrab').mousedown(function(e){
        cursordown = true; 
        cursorxpos = $(this).scrollLeft() + e.clientX; 
        cursorypos = $(this).scrollTop() +e.clientY;
      }).mousemove(function(e){
        if(!cursordown) return;
        try { $(this).scrollLeft(cursorxpos - e.clientX); } catch(e) { }
        try { $(this).scrollTop(cursorypos - e.clientY); } catch(e) { }
      }).mouseup(end = function(e){
        cursordown = false;
      }).mouseleave(end)
        .css('user-select', 'none')
        .css('cursor', 'grab');

针对水平和垂直滚动进行了全面验证
您只需将**.cursorgrab**class设置到元素中

wh6knrhe

wh6knrhe9#

香草JS:

var clicked = false, clickY, clickX;
document.onmousemove = (e) => {
  clicked && updateScrollPos(e);
}
document.onmousedown = (e) => {
  clicked = true;
  clickY = e.pageY;
  clickX = e.pageX;
  document.querySelector("body").style.userSelect = "none";
}
document.onmouseup = (e) => {
  clicked = false;
  document.querySelector('html').style.cursor='grab';
}
var updateScrollPos = function(e) {
  document.querySelector('html').style.cursor='grabbing';
  window.scrollTo(window.scrollX + (clickX - e.pageX), window.scrollY + (clickY - e.pageY));
}

相关问题