如何在触发“touchstart”事件时阻止“滚动”

时间:2014-11-20 15:36:20

标签: javascript html

我有一个可滚动的元素,我添加了两个事件处理程序(“touchstart”和“scroll”)。如果自己解雇,两者都可以完美地运行但是,当触发“touchstart”事件时,我需要阻止“滚动”被触发,但我仍然需要“滚动”事件可用。原因是两个事件都调用相同的函数,因此当逻辑运行多次时,它会导致应用程序出现错误。

我创建了一个基本的小提琴,这里是链接:

http://jsfiddle.net/alejandro1585/0t7v76m7/3/

HTML:

 <div class="main-container">
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
</div>

CSS:

.main-container{
    border:  1px solid red;
    width: 120px;
    height:200px;
    overflow-y: auto;
}

JAVASCRIPT:

    function myFunction(e) {
    console.log("myFunction is being executed", e);
};

/*Method adds handlers to the scrollable list so that functions to show or hide the header can be triggered*/
var scrollShowHideHeaderInit = function () {
    var divObject = document.getElementsByClassName("main-container"); //Scrollable element object

    for (var i = 0; i < divObject.length; i++) {
        divObject[i].addEventListener("scroll", myFunction);
        divObject[i].addEventListener("touchstart", myFunction);
    };
};

scrollShowHideHeaderInit();

1 个答案:

答案 0 :(得分:0)

你应该能够在触摸开始时停止事件传播并仍然保持滚动能力

function touch(e){
  console.log("touch", e);
  e.stopPropagation();
};