如何防止 :focus/:active 上显示的链接在触摸屏上自动点击?

How to prevent links displayed on :focus/:active from auto-clicking on a touch screen?

我正在设计一个侧边栏,它会隐藏菜单条目,除非用户将鼠标悬停在它上面/或在移动设备上点击它。问题发生在移动设备上(或者当我在 chrome 中测试我的代码并在开发人员选项中切换移动模式时)。在触摸模式下,如果我点击焦点后将显示菜单条目的侧边栏,则会自动单击新显示的菜单条目。有没有办法禁止自动点击指针下新出现的链接?

我的首选解决方案是纯粹的 CSS - 但如果没有其他选择,我可以使用 vanilla JS。

这是我的fiddle:https://jsfiddle.net/n7nsdL49/

HTML:

<div class="sidebar">
    <div class="menu">
        <ul class="menu">
            <li><a href="http://www.google.com" target="_blank">This</a></li>
            <li><a href="http://www.google.com" target="_blank">is</a></li>
            <li><a href="http://www.google.com" target="_blank">a</a></li>
            <li><a href="http://www.google.com" target="_blank">menu.</a></li>
        </ul>
    </div>
</div>

CSS:

.sidebar {
  position: fixed;
  height: 100%;
  width: 10%;
  background-color : green;
}
.menu {
  display: none
}
.sidebar:hover, .sidebar:focus {
  width: 20%;
  background-color: red;
}
.sidebar:hover .menu, .sidebar:focus .menu {
  display: block;
}

编辑: 我试过 pointer-events 选项,但它似乎对显示时自动点击的链接没有影响。

我的建议是避免摆弄显示器,而是使用以下方法将其隐藏在左侧:

.sidebar {
  position: fixed;
  height: 100%;
  width: 40%;
  background-color : green;
  left:-20%;
}

.sidebar:hover, .sidebar:focus {
  background-color: red;
  left:0;
}

这是一个fiddle:https://jsfiddle.net/n7nsdL49/2/

您甚至可以添加过渡

.sidebar {
  position: fixed;
  height: 100%;
  width: 40%;
  background-color : green;
  left:-20%;
  transition: left 0.2s ease-in;
}

我能够通过使用 animation 属性 绕过自动点击新可见的 links。本质上,我将 menu class 动画化为在获得 focushover 后的一小段时间可见。这样,如果新显示的 link 位于指针事件下方,则点击不会注册。这是 fiddle: https://jsfiddle.net/nu9vr1sm/.

HTML:

<div class="sidebar">
    <div class="menu">
        <ul class="menu">
            <li><a href="http://www.google.com" target="_blank">This</a></li>
            <li><a href="http://www.google.com" target="_blank">is</a></li>
            <li><a href="http://www.google.com" target="_blank">a</a></li>
            <li><a href="http://www.google.com" target="_blank">menu.</a></li>
        </ul>
    </div>
</div>

CSS:

.sidebar {
  position: fixed;
  height: 100%;
  width: 10%;
  background-color : green;
}
.menu {
  display: none;
  visibility: hidden;    /* <= include this property */
}
.sidebar:hover, .sidebar:focus {
  width: 20%;
  background-color: red;
}

/* ================== */
/* THE IMPORTANT PART */
/* ================== */
.sidebar:hover .menu,
.sidebar:focus .menu {
        display: block;                /* make it part of the DOM */
        animation: fadeIn 0.05s;       /* make it visible after a while */
        animation-fill-mode: forwards; /* make it retain final visibility */
    }

@keyframes fadeIn {
  99% {
    visibility: hidden;
  }
  100% {
    visibility: visible;
  }
}
/* ================== */