我正在根据分析团队的要求修改 UI 代码。所有可点击元素必须是 a
或 button
。
我已经覆盖了 button
和 a
样式,因此它们看起来没有任何不同。在桌面浏览器中,它们的行为似乎也没有不同。
但是从开发工具打开 chrome 的“设备模拟”,你可以看到 button
和 a
元素有不同的行为。它们各自的目标点击区域似乎更小,你必须直接点击svg“X”而不是 block 级元素的任何部分。
我已经尝试了 a
和 button
元素。我还在 jsfiddle 中重现了这个问题。
这个 jsfiddle 重现了这个问题(在 chrome 的移动设备模拟器模式下测试)https://jsfiddle.net/8jze13t0/1/
// script.js
let i = 0;
const closeBtns = document.querySelectorAll('.close');
const clickCount = document.querySelector('.click-count');
Array.from(closeBtns).forEach(btn => btn.addEventListener('click', (e) => {
e.preventDefault();
i++;
clickCount.innerText = i;
}))
clickCount.innerText = i;
body {
background: darkBlue;
color: white;
font-family: sans-serif;
}
.close {
margin-top: 10px;
white-space: nowrap;
text-indent: 100%;
overflow: hidden;
background: url("data:image/svg+xml;charset=utf-8,%3Csvg width='20' height='20' viewBox='0 0 20 20' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M10.4809 10.0128L19.9119 0.579492C20.0423 0.479492 20.0423 0.246029 19.9119 0.112695C19.7819 -0.020638 19.5709 -0.020638 19.4406 0.112695L10.0096 9.54564L0.578599 0.112695C0.448599 -0.020638 0.237599 -0.020638 0.107266 0.112695C-0.0227344 0.246029 -0.0227344 0.479492 0.107266 0.579492L9.53826 10.0128L0.107266 19.4457C-0.0227344 19.5794 -0.0227344 19.8128 0.107266 19.9128C0.172599 19.9795 0.257599 20.0128 0.342933 20.0128C0.428266 20.0128 0.513599 19.9795 0.578599 19.9128L10.0096 10.5128L19.4406 19.9128C19.5059 19.9795 19.5909 20.0128 19.6763 20.0128C19.7616 20.0128 19.8469 19.9795 19.9119 19.9128C20.0423 19.8128 20.0423 19.5794 19.9119 19.4457L10.4809 10.0128Z' fill='white'/%3E%3C/svg%3E");
width: 20px;
height: 20px;
margin-right: 16px;
display: block;
}
button {
outline: 0;
border: 0;
background: none;
padding: 0;
font-family: inherit;
font-style: inherit;
cursor: pointer;
}
<p>
Click Count:
<span class="click-count">
</span>
</p>
<p>
First Example With `div:`
<div class="close">
Close me
</div>
</p>
<p>
Second Example With `button`
<button class="close">
Close me
</button>
</p>
<p>
Third Example With `a`
<a href="#close" class="close">
Close me
</a>
</p>
这是问题的屏幕截图(带注释):
我希望能够点击移动模拟器中 block 级元素内的任意位置并触发事件处理程序。
最佳答案
删除文本及其关联的样式
删除这些额外的规则
white-space: nowrap;
text-indent: 100%;
overflow: hidden;
还要从 html 中删除文本,如果你不打算使用它,为什么要有它
如果你想要屏幕阅读器的文本,你可以在元素上使用 aria-label="whatever"
<a href="whatever" aria-label="whatever label">
关于javascript - 为什么此按钮元素与 div 具有不同的 'click' 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55404502/