2014-12-08 96 views
1

我想在我的html5页面上添加一个触摸事件到img控件。将触摸事件添加到html img控件

这是我到目前为止有:

<img 
    src="Images/Home-icon.png" 
    onclick="Menu_Click('Home');" 
    ontouchend="Menu_Click('Home');" 
    draggable="false" 
    cssclass="iconImageStyle" 
    style="cursor: pointer;" 
    alternatetext="Home" 
    tooltip="Home" 
    height="32" 
    width="32" /> 

从一个正常的Web浏览器中单击事件工作正常。 但是,当我尝试从我的ipad访问它时,它没有反应。

帮助将非常受欢迎。


编辑1

不过至今没有运气。 我试图用div来包围img,并将touchend事件添加到div,但它没有响应它。


编辑2

我也跟着上我的iPad作品的教程。 基本上,本教程是一个画布,显示画布内触摸事件的坐标。 我只是将画布和javascript添加到我的页面,并让它重叠我的一些img按钮。 我的页面对触摸事件作出反应,画布正确显示坐标。 现在,这是它越来越奇怪。 画布内出现的按钮现在对触摸结束事件作出反应,但实际上会触发onclick事件! 不在画布里面没有任何东西反应同样的按钮...

这是教程代码我在页

<script type="text/javascript"> 
    var can, ctx, canX, canY, mouseIsDown = 0; 
    function init() { 
     can = document.getElementById("can"); 
     ctx = can.getContext("2d"); 
     document.body.addEventListener("mouseup", mouseUp, false); 
     document.body.addEventListener("touchcancel", touchUp, false); 
    } 
    function mouseUp() { 
     mouseIsDown = 0; 
     mouseXY(); 
    } 

    function touchUp() { 
     mouseIsDown = 0; 
     // no touch to track, so just show state 
     showPos(); 
     } 

    function mouseDown() { 
     mouseIsDown = 1; 
     mouseXY(); 
     } 

    function touchDown() { 
     mouseIsDown = 1; 
     touchXY(); 
     } 

    function mouseXY(e) { 
     if (!e) 
     var e = event; 
     canX = e.pageX - can.offsetLeft; 
     canY = e.pageY - can.offsetTop; 
     showPos(); 
     } 

    function touchXY(e) { 
     if (!e) 
     var e = event; 
     e.preventDefault(); 
     canX = e.targetTouches[0].pageX - can.offsetLeft; 
     canY = e.targetTouches[0].pageY - can.offsetTop; 
     showPos(); 
     } 

    function showPos() { 
     // large, centered, bright green text 
     ctx.font = "24pt Helvetica"; 
     ctx.textAlign = "center"; 
     ctx.textBaseline = "middle"; 
     ctx.fillStyle = "rgb(64,255,64)"; 
     var str = canX + ", " + canY; 
     if (mouseIsDown) 
     str += " down"; 
     if (!mouseIsDown) 
     str += " up"; 
     ctx.clearRect(0, 0, can.width, can.height); 
     // draw text at center, max length to fit on canvas 
     ctx.fillText(str, can.width/2, can.height/2, can.width - 10); 
     // plot cursor 
     ctx.fillStyle = "white"; 
     ctx.fillRect(canX - 5, canY - 5, 10, 10); 
     } 

</script> 
<canvas id="can" height="200" width="300" style="background-color: black"> 
</canvas> 

我将继续调查粘贴。 但从看起来像我将不得不把我的按钮后面的画布... 我宁愿避免,如果可能的话,但到目前为止我没有看到任何其他解决方案。 如果有效,我会将其作为解决方案发布,除非有人比我更聪明可以提出更好的建议。


编辑3

本人确认的JavaScript是没有用的。 只需在img后面放置画布,就可以响应点击事件。 我不知道为什么会发生这种情况,但我会一直这样做,直到找到更好的解决方案。 如果有人作为解释或更好的解决方案,欢迎您发布它。

回答

0

好的,终于搞清楚了。 如果您对元素使用绝对位置,看起来像Touch Events无法正常工作。 我使用CSS修改了我的div表格布局,现在一切正常。