如何阻止标签阻止输入元素内的用户输入

DR0*_*01D 2 css

在下面的简化示例中,我使用绝对定位将标签放在输入元素内.我使用JavaScript来使标签缩小或增长,具体取决于焦点/模糊.这按预期工作.

我的问题:如果我单击文本标签,它会阻止焦点在输入元素上,标签不会缩小.如果我单击元素内的任何其他位置,它将按预期工作.我试图Z-index -1将标签放在输入框后面,但这并没有解决问题.我也试过user-select: none但它仍然阻止了对输入元素的关注.有没有办法阻止标签阻止输入元素?

document.querySelector('input').addEventListener('focus', labelShrink);
document.querySelector('input').addEventListener('blur', labelGrow);

function labelShrink() {
    document.querySelector('.inputLabel').style.fontSize = ".75rem";
}

function labelGrow() {
    if (!document.querySelector('.inputField').value) {
        document.querySelector('.inputLabel').style.fontSize = "1.5rem";
    } 
}
Run Code Online (Sandbox Code Playgroud)
.inputContainer {
    position: relative;
}

.inputLabel {
    position: absolute;
    z-index = -1; 
    padding: .25rem 0 0 .25rem;
    font-size: 1.5rem;
    user-select: none;
    transition: font-size .25s;
}

.inputField {
    padding: .75rem 0 0 0;
    font-size: 2rem;
    background-color: transparent;
}
Run Code Online (Sandbox Code Playgroud)
<div class="inputContainer">
  <label class="inputLabel" for="userName">User Name</label>
  <input class="inputField" type="text" name="userName">
</div>
Run Code Online (Sandbox Code Playgroud)

Sup*_*rDJ 5

添加pointer-events: none;到标签,以便您可以单击它.

document.querySelector('input').addEventListener('focus', labelShrink);
document.querySelector('input').addEventListener('blur', labelGrow);

function labelShrink() {
    document.querySelector('.inputLabel').style.fontSize = ".75rem";
}

function labelGrow() {
    if (!document.querySelector('.inputField').value) {
        document.querySelector('.inputLabel').style.fontSize = "1.5rem";
    } 
}
Run Code Online (Sandbox Code Playgroud)
.inputContainer {
    position: relative;
}

.inputLabel {
    position: absolute;
    z-index = -1; 
    padding: .25rem 0 0 .25rem;
    font-size: 1.5rem;
    user-select: none;
    transition: font-size .25s;
    pointer-events: none; // Add this line
}

.inputField {
    padding: .75rem 0 0 0;
    font-size: 2rem;
    background-color: transparent;
}
Run Code Online (Sandbox Code Playgroud)
<div class="inputContainer">
  <label class="inputLabel" for="userName">User Name</label>
  <input class="inputField" type="text" name="userName">
</div>
Run Code Online (Sandbox Code Playgroud)

  • 来自 mozilla 的 @DR01D :“元素永远不是鼠标事件的目标;” (2认同)