JavaScript-在手机上不工作的情况下,在外部单击时隐藏元素

JavaScript - hide element when click outside not working on mobile phone

本文关键字:单击 外部 隐藏 元素 手机 工作 JavaScript- 情况下      更新时间:2023-09-26

使用此代码,隐藏模式窗口在台式机上运行良好

$(document).mouseup(function (e){
    if ($("#full_window_dim").is(':visible') && !$("#hodnotenie_hl_okno").is(e.target) && $("#hodnotenie_hl_okno").has(e.target).length === 0){
        $("#full_window_dim").fadeOut();
        $('html, body').removeClass('stop-scrolling');
}
});

但是这个代码在手机上不起作用(我试过iPhone 5-Safari)

当用户在手机上点击窗外时,我如何隐藏元素?

您可以对手机使用touchstart,因为大多数设备都不了解鼠标事件。

这是代码。您可以包含任意数量的活动。

function HideModal(){
    if ($("#full_window_dim").is(':visible') && !$("#hodnotenie_hl_okno").is(e.target) && $("#hodnotenie_hl_okno").has(e.target).length === 0){
        $("#full_window_dim").fadeOut();
        $('html, body').removeClass('stop-scrolling');
    }
}
 $(document).on({
        "touchstart": function (event) { HideModal(); },
        "mouseup": function (event) { HideModal(); }
});

您可以为移动css定义"body{cursor:pointer}",然后将Safari mobile行为定义为单击,而不是点击。但我不确定这是否是一种最佳方式。我只是尝试了一下,并为我工作。