按钮在iPhone上无法正常工作(可能还有其他触摸屏)

Button not working properly on iPhone (and possibly other touch screens)

本文关键字:触摸屏 其他 工作 按钮 常工作 iPhone      更新时间:2023-09-26

我有一个Map按钮,您可以单击(或点击)它来显示带有嵌入式Google Map的模态。在不同的浏览器中,它在桌面上的工作原理是一样的,但在iPhone(可能还有其他触摸屏)上,我必须点击两次按钮。

编辑:尝试使用"ontouchend"作为触发器,使用"touchend"关闭模态。现在模态一打开就关闭。

HTML:

<div class="map-modal" id="map-modal">
    <div class="map-container">
        <div class="the-map" id="map-canvas"></div>
        <div class="hide-btn hide-btn--map" onclick="closeModal();"><span class="close hairline"></span><div class="hidden-content">Hide the map</div></div>
    </div>
</div>

按钮:

<div class="button button--map" onmousedown="calcRoute('<?php echo $location[address1]; ?>', '<?php echo $location[address2]; ?>');">Map</div>

JavaScript:

function calcRoute(start, end) {
    var e = document.getElementById("map-modal");
    e.style.display = 'block';
    $("body").addClass("modal-open");
    google.maps.event.trigger(map, 'resize');
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.TravelMode.WALKING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        } else {
            alert("Sorry, no walking route can be found between these locations");
        }
    });
}
google.maps.event.addDomListener(window, 'load', initialize);

听起来像touchstart和mousedown都在开火。此线程具有一些选项,用于在移动设置中抑制mousedown事件。onclick和ontouchstart同时启动

解决方案(不完美)

解决方案已更新,请参阅下文。

通过发送带有触发事件的布尔变量来捕捉"第二次"触摸。对于ontouchstart,设置touch=true,对于onclick,设置touched=false。然后在模式关闭功能中,检查是否有触摸事件,并重置触摸的变量

这不是一个优雅的解决方案。如果谷歌地图的标志恰好位于用户触摸屏幕打开地图的位置,它会注册为额外的触摸,谷歌地图应用程序就会打开

解决方案是防止事件在DOM树中冒泡(我以前从未听说过事件冒泡)。在谷歌上搜索并发现这一点,为我指明了正确的方向。这很简单。只需在事件触发器上使用this.stopPropagation();

我在这篇文章中保留了以前的解决方案,以展示我所尝试的,并可能让男性更容易理解事件传播(或"事件冒泡")在这种情况下是如何工作的。

如果有人有更优雅的解决方案,请随时分享。

触发器事件按钮

<div class="button button--map right"
    ontouchstart="this.stopPropagation(); calcRoute('Citybox+Oslo,+Prinsens+gate+6,+0152+Oslo,+Norway', '<?php echo $location[address]; ?>');"
    onclick="calcRoute('Citybox+Oslo,+Prinsens+gate+6,+0152+Oslo,+Norway', '<?php echo $location[address]; ?>');"
    >Map</div>