1

我叫尼克。我正在开发一个 Web 应用程序,其中包含一个包含在 div 中的下拉菜单,该菜单具有绝对位置和滚动溢出-y 的样式。如果用户想从菜单中看到更多选项(文本),他们需要向下滚动(使用鼠标滚轮或手指在触摸设备上)。

我的网络应用程序在所有流行的(台式机/笔记本电脑)网络浏览器、iPad 和 iPhone 上运行良好,但菜单在 Android(智能手机和平板电脑)上不可滚动。我尝试使用 Chris 的想法(http://chris-barr.com/index.php/entry/scrolling_a_overflowauto_element_on_a_touch_screen_device/)和 Tom 的(如何让 Android 响应触摸拖动?)来处理触摸事件,但它仍然没有奏效。

大家能给我一些提示来解决这个问题吗?您的帮助将不胜感激。

我只使用 HTML5、CSS 和 jQuery。下面给出的功能适用于您希望使其在触摸设备上滚动的信息提供(文本 + 图像)div 容器。

这是我的自定义代码:

/* Make scrollable texts scrollable on touch devices */

function touchScroll(id, option) {
    var scrollStartPosY = 0, scrollStartPosX = 0;
    var element = document.getElementById(id), jQueryId = '#' + id, jQueryElement = $(jQueryId);
    if (!element) {
        return;
    }

    if (option == "disable") {
        jQueryElement.unbind("touchstart");
        jQueryElement.unbind("touchmove");
        return;
    }

    /*
     * Note that Android browser doesn't support a web app featuring divs with overflow: scroll styling.
     * So we need to use touches and drags with our own custom functions
     */

    jQueryElement.bind("touchstart", function(event) {
        scrollStartPosY = jQueryElement.scrollTop() + event.originalEvent.touches[0].pageY;
        scrollStartPosX = jQueryElement.scrollLeft() + event.originalEvent.touches[0].pageX;
        event.preventDefault();
    });

    jQueryElement.bind("touchmove", function(event) {
        // These if statements allow the full page to scroll (not just the div) if they are
        // at the top of the div scroll or the bottom of the div scroll
        // The -5 and +5 below are in case they are trying to scroll the page sideways
        // but their finger moves a few pixels down or up.  The event.preventDefault() function
        // will not be called in that case so that the whole page can scroll.
        if (((jQueryElement.scrollTop() < (element.scrollHeight - element.offsetHeight)) &&
            ((jQueryElement.scrollTop() + event.originalEvent.touches[0].pageY) < scrollStartPosY - 5)) ||
            (jQueryElement.scrollTop() != 0 && ((jQueryElement.scrollTop() + event.originalEvent.touches[0].pageY) > (scrollStartPosY + 5)))) {
            event.preventDefault();
        }
        if (((jQueryElement.scrollLeft() < (element.scrollWidth - element.offsetWidth)) &&
            ((jQueryElement.scrollLeft() + event.originalEvent.touches[0].pageX) < (scrollStartPosX - 5))) ||
            (jQueryElement.scrollLeft() != 0 && ((jQueryElement.scrollLeft() + event.originalEvent.touches[0].pageX) > (scrollStartPosX + 5)))) {
            event.preventDefault();  
        }

        jQueryElement.scrollTop (scrollStartPosY - event.originalEvent.touches[0].pageY);
        jQueryElement.scrollLeft (scrollStartPosX - event.originalEvent.touches[0].pageX);
    });
}
4

0 回答 0