繁体   English   中英

iFrame中的触摸事件无法在iOS上运行

[英]Touch events within iFrame are not working on iOS

当连接到iOS设备上的IFrame内的窗口时,触摸事件(如touchstarttouchend不会触发。

这是一个非常简单的例子:

parent.html

<!DOCTYPE HTML>
<html style="height: 100%;">
<head>
    <meta charset="UTF-8">
    <title>Touch Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body style="height: 100%; margin: 0; overflow: hidden;">
    <iframe style="width: 100%; height: 100%; border: none;" src="child.html"></iframe>
</body>
</html>

child.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>Touch Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style>    
        body {
            margin: 0;
            padding: 8px;
        }

        div.header {
            margin-bottom: 8px;
        }

        div.text-entry {
            font: 300 1rem/1.25 'Open Sans', 'Helvetica Neue', helvetica, arial, sans-serif;
            color: rgb(64, 64, 64);
        }
    </style>

    <script>
        window.onload = function() {
            function addEvent(event) {
                var div = document.createElement('div');

                div.className = 'text-entry';
                div.textContent = new Date().toLocaleTimeString() + ' Event "' + event.type + '" detected';
                document.body.appendChild(div);
            }

            window.addEventListener('touchstart', addEvent.bind(null), false);
            window.addEventListener('touchend',   addEvent.bind(null), false);
        }
    </script>
</head>
<body>
    <div class="text-entry header">Clicks/touches on the viewport should add some text entries...</div>
</body>
</html>

我在IFrames中找到了有关iOS上滚动问题的多个问题,有些关于事件的问题,但似乎没有一个问题可以解决我现在遇到的问题。

我为每个人创建了一个CodePen和一个JSFiddle ,它们显示了完全相同的行为,因为它们都在IFrame中执行代码。

解决方案1:在iframe内部,向文档对象添加一个虚拟侦听器:

document.addEventListener('touchstart', {}); // in iframe

似乎IOS上的Safari拒绝将侦听器触摸到窗口,除非其他DOM对象也有侦听器。

解决方案2:在顶部窗口内,向任何对象(包括窗口 )添加一个虚拟侦听

window.addEventListener('touchstart', {}); // in top window

似乎IOS上的Safari拒绝在iframe中触摸侦听器窗口,除非父级也有侦听器。

上述任何一种解决方案都有效(它们不是都需要,只有一种)。 测试:

  • Safari 9.0 / IOS:9.3.5
  • Safari 11.0 / IOS:11.3

将以下CSS添加到IFrame内容(上例中的child.html)为我解决了这个问题:

html, body {
    touch-action: auto;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM