我有一个<label>
与 ::after
附加到它的伪元素,我想将 click
绑定(bind)到它事件。
<label for="my-input">
<input id="my-input" />
</label>
由于伪元素不是 DOM 的一部分,我显然不能这样做,所以我绑定(bind)了 click
事件至<label>
相反。
但是...我们都知道<label>
是什么是吗?是的,它重新聚焦光标在 <input>
上.
所以,如果您已经猜到会发生什么,那就太好了 - 事件触发两次。
为什么?因为当用户单击<label>
时它会触发一次然后浏览器会自动单击 <input>
(重新定位光标),最终会再次触发该事件。
我很想知道是否有任何创造性的方法来解决这个问题。
通常,您可以通过更改 useCapture
在冒泡阶段停止事件触发。 .addEventListener()
末尾的 bool 标志来自false
至true
- 但在这种情况下,当浏览器自动单击 <label>
时,这不会阻止事件(绑定(bind)到 <input>
)第二次触发。 .
工作示例:
var myInput = document.querySelector('label[for="my-input"]');
var clickNumber = 1;
function clickDetected(event) {
console.log('Click ' + clickNumber + ' detected');
clickNumber++;
}
myInput.addEventListener('click', clickDetected, false);
label {
position: relative;
top: 48px;
width: 200px;
height: 100px;
margin: 24px 6px;
padding: 24px;
background-color: rgb(255, 0, 0);
}
label[for="my-input"]::after {
content: '+';
position: absolute;
display: block;
top: -26px;
right: 4px;
width: 22px;
height: 22px;
color: rgb(255, 255, 255);
font-size: 21px;
line-height: 22px;
font-weight: bold;
text-align: center;
background-color: rgb(255, 0, 0);
border-radius: 2px;
box-shadow: 3px 3px 3px rgba(0, 75, 165, 0.4);
cursor: pointer;
}
<label for="my-input">
<input id="my-input" type="text" />
</label>
最佳答案
这样做:
var myInput = document.querySelector('label[for="my-input"]');
var clickNumber = 1;
function clickDetected(e) {
}
myInput.onclick = function (e) {
if (e.target.getAttribute('id') === 'label') {
console.log('Click ' + clickNumber + ' detected');
clickNumber++;
}
}
label {
position: relative;
top: 24px;
width: 200px;
height: 100px;
margin: 24px 6px;
padding: 24px;
background-color: rgb(255, 0, 0);
}
<label for="my-input" id="label">
<input id="my-input" type="text" />
</label>
关于javascript - 将事件绑定(bind)到没有事件的 <label> 然后触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47781056/