简体   繁体   English

阻止元素从移动设备上拖离屏幕

[英]Stop element from being dragged off screen on mobile device

I have an element that can be dragged up/down. 我有一个可以向上/向下拖动的元素。 If the user is at the top of the page, the element ( div ) will stop dragging when it gets 50px from the top (same for bottom if user is scrolled all the way to the bottom). 如果用户位于页面顶部,则元素( div )从顶部获得50px时将停止拖动(如果用户一直滚动到底部,则与底部相同)。

The Problem: If the user scrolls down the page just a little then the div can be dragged out of view. 问题:如果用户仅向下滚动页面一点,则div可以拖出视图。 I would like for it to stop before it goes out of view from the top and the bottom. 我希望它在从顶部和底部消失之前停下来。 Picture cell phone screen, you can drag a little box on right side of your screen up/down, but can't drag it out of view, even when you scroll up/down the page. 在图片手机屏幕上,您可以向上/向下拖动屏幕右侧的一个小框,但是即使向上/向下滚动页面也不能将其拖到视线之外。

I know I need to figure out whether the page is scrolled then subtract that from the document height, etc, etc...(or something like that). 我知道我需要弄清楚页面是否滚动,然后从文档高度中减去它,等等,等等(或类似的东西)。 Or maybe there is a better solution I don't know about. 也许有一个我不知道的更好的解决方案。

Here is what I have so far that makes the div draggable along the y axis: 到目前为止,这是使div 沿y轴拖动的内容:

    this.makeDraggable = function(){
        var docHeight = $(document).height();
        var winHeight = $(window).height();

        if(eventSupported('touchstart')){
            el.addEventListener("touchmove", handleMove, false);
        }

        function handleMove(e) {
            e.preventDefault();
            var y = e.changedTouches[0].pageY;
            var bottom = winHeight - y;

            if(bottom > 50 && y > 50)
            $el.offset({
                top: y
            });
        }
    }

Found the solution: 找到了解决方案:

 this.makeDraggable = function(){
        var docHeight = $(document).height();
        var winHeight = $(window).height();

        if(eventSupported('touchstart')){
            el.addEventListener("touchmove", handleMove, false);
        }

        function handleMove(e) {
            e.preventDefault();

            var winScroll = $(window).scrollTop(); // scrolled away from top
            var y = e.changedTouches[0].pageY;
            var top = winScroll + 50;
            var bottom = winScroll + winHeight - 50;

            if(bottom > y && y > top)
            $el.offset({
                top: y
            });
        }
    }

$(window).scrollTop() + $(window).height() is always going to be the bottom of the "window". $(window).scrollTop()+ $(window).height()始终是“窗口”的底部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM