-1

我正在创建一个 Android 应用程序并有 2 个按钮。1个开始和1个停止。单击开始按钮后,停止按钮开始可见,然后停止按钮变为可见并开始不可见。

我试图在 STOP 按钮上获得一个 touchstart 事件(也可以添加到开始按钮,但不是必需的)。但是,由于某种原因,我的以下代码无法正常工作。有些人可以让我知道我错过了什么。

背景: - 使用 jquery 隐藏我的按钮 - 带有背景图像的按钮

JAVASCRIPT:

var b=document.getElementById('STOP'),start=0;

//Check for touchstart
if('ontouchstart' in document.documentElement) 
{
    document.getElementById("notouchstart").style.display = "none";
}

//Add a listener that fires at the beginning of each interaction
[b].forEach(function(el){el.addEventListener('touchstart',interact);});

//Add the event handlers for each button
b.addEventListener('touchstart',highlight);

//Functions Store the time when the user initiated an action
function interact(e) 
{
    start = new Date();
}

//Highlight what the user selected and calculate how long it took the action to occur
function highlight(e) 
{
    e.preventDefault();
    e.currentTarget.className="active";
    if(start)
    {
        alert("test")
    }
    start = null;
}

HTML 按钮:

<INPUT TYPE="button" style="background:url(images/Start_Btn.png); background-color:transparent; width:150px; height:186px; border:none; cursor:pointer;" id="START" onClick="startBTN();">
<INPUT TYPE="button" style="background:url(images/Stop_Btn.png); background-color:transparent; width:150px; height:186px; border:none; cursor:pointer;" id="STOP">
4

2 回答 2

0

我已经解决了我的问题,我试图变得太聪明。我只需要 onload 函数中的两行代码:

    function onload()
    {
    /* PART 1 - sets touch even to button
       PART 2 - Defines what JavaScript function to run
       PART 3 - Indicates to set the touch event to false on first load */
        document.getElementById('START').addEventListener('touchstart', startBTN, false);
        document.getElementById('STOP').addEventListener('touchstart', stop, false);
    }

调用函数 onload:

<body  onload="onload();">
     //HTML CONTENT
</body>

希望这可以帮助某人

于 2012-02-23T12:48:21.960 回答
0

您在相同的元素上有两个touchstart事件。因此,它正在interact同时执行highlight。这是故意的吗?此外,您没有传递event到您的highlight(e)函数中。您需要将其包装在传递它的匿名函数中:

b.addEventListener('touchstart',function(e) { highlight(e); }, false);

另外,不要忘记添加false到您的addEventListener声明中。

编辑:我们不想为touchstart同一个元素设置两个事件监听器。我们需要修改forEach语句以及highlight函数。

var b = document.getElementById('STOP');
var c = document.getElementById('START');
var array = [b, c];

array.forEach(function(element, index, array) {
  element.addEventListener('touchstart', function(event){ highlight(event); }, false);
});

function highLight(event) {
  start = new Date(); // not sure what you're trying to accomplish here
  event.preventDefault();
  event.currentTarget.setAttribute('class', 'active');
  if(start) {
    alert("test")
  }
  start = null;
}
于 2012-02-21T16:24:51.190 回答