【问题标题】:JavaScript prevent touch move on body element, enable on other elementsJavaScript 防止在 body 元素上触摸移动,在其他元素上启用
【发布时间】:2013-08-16 13:11:50
【问题描述】:

但非常简单,我想阻止 body 元素上的 touchmove 事件,但为另一个元素启用它。我可以禁用它...但我不确定如何在其他地方重新启用它!

我想下面的理论上可行,因为return truepreventDefault 相反,但它对我不起作用。可能是因为 $altNav 元素是 in $bod?

JS:

$bod.bind('touchmove', function(event){

    event.preventDefault();
});
$altNav.bind('touchmove', function(event){

    return true;
});

【问题讨论】:

标签: javascript events default event-propagation touchmove


【解决方案1】:

我不确定你实际使用的是什么库,但我会假设 jQuery(如果你使用的不是 jQ,我也会在 browser-native-js 中发布相同的代码)

$bod.delegate('*', 'touchstart',function(e)
{
    if ($(this) !== $altNav)
    {
        e.preventDefault();
        //and /or
        return false;
    }
    //current event target is $altNav, handle accordingly
});

这应该可以解决所有问题。此处的回调处理所有 touchmove 事件,并在每次事件在$altNav 以外的元素other 上触发时调用preventDefault 方法。

在 std browser-js 中,此代码类似于:

document.body.addEventListener('touchmove',function(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    //in case $altNav is a class:
    if (!target.className.match(/\baltNav\b/))
    {
        e.returnValue = false;
        e.cancelBubble = true;
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        return false;//or return e, doesn't matter
    }
    //target is a reference to an $altNav element here, e is the event object, go mad
},false);

现在,如果 $altNav 是具有特定 id 的元素,只需将 target.className.match() 替换为 target.id === 'altNav' 等等...
祝你好运,希望这会有所帮助

【讨论】:

    【解决方案2】:

    使用自定义 CSS 类并在文档处理程序中对其进行测试,例如:

    <div>
        This div and its parents cannot be scrolled.
        <div class="touch-moveable">
            This div and its children can.
        </div>
    </div>
    

    然后:

    jQuery( document ).on( 'touchmove', function( ev )
    {
        if (!jQuery( ev.target ).parents().hasClass( 'touch-moveable' ))
        {
             ev.preventDefault();
        }
    });
    

    http://tinyurl.com/mo6vwrq

    【讨论】:

      【解决方案3】:

      你可以像这样添加一个参数

      $bod.bind('touchmove', function(event,enable){
         if(enable){
             event.preventDefault();
         }
      
      });
      

      【讨论】:

        猜你喜欢
        • 2012-12-01
        • 2017-01-03
        • 1970-01-01
        • 2013-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多