触摸事件对位置:固定;元素在 iOS 上无法正常工作

Touch event on position: fixed; element doesn't work correctly on iOS

本文关键字:常工作 工作 iOS 位置 事件 固定 元素 触摸      更新时间:2023-09-26

这是IOS 5(safari)错误的类似问题,在"位置:固定"div上有HTML触摸事件

有人说这个错误已经修复了。但是,在iOS 8上,我发现只有当您缓慢点击并滚动页面时,它才会被修复。

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <title>Document</title>
    <style>
    header {
        position: fixed;
        width: 100%;
        height: 600px;
        top: 0;
        color: #fff;
        background: rgba(0, 0, 0, 0.9);
        z-index:100;
    }
    .content {
        height: 10000px;
        background: url(http://placehold.it/350x150&text=Background);
    }
    </style>
</head>
<body>
    <header></header>
    <section class="content"></section>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
        (function($) {
            'use strict';
            $('header').on('touchend', function(event) {
                event.stopPropagation();
                $('<p>Tap on float content.</p>').appendTo('header');
                // hack 1
                var $temp = $('<div style="height: 20000px"></div>');
                $temp.appendTo('body');
                setTimeout(function(){
                    $temp.remove();
                }, 1);
            });
            $(document).on('touchend', function() {
                $('<p>Tap on UNDER content.</p>').appendTo('header');
            });
            // hack 2
            $('body').bind('touchstart', function(e) {});
        }(jQuery));
    </script>
</body>
</html>

您可以通过以下两种不同的方式找到该错误:

  • 快速滑动并滚动<head>区域上的页面几次。
  • 在 .content 区域上滑动,然后在页面停止滚动之前快速点击<header>区域。

在这两种情况下,有时您会发现"点击下方内容"是当您点击<header>区域时输出的。

更新:

有第三种情况:

  • 在 .content 区域上滑动,然后在页面停止滚动之前再次快速点击 .content 区域,然后点击<header>区域。在这种情况下,<header>区域上的点击不会输出任何内容。

我尝试过这些技巧,例如"为<body>添加触摸启动事件","添加临时<div>"。它们都不起作用。

关于如何解决这个问题的任何想法?谢谢。

如果你有一个带有 position:fixed 的元素,并且触摸事件不起作用,请尝试添加:

pointer-events: none;