这个任务看起来很简单,所以我希望找到一个简单的解决方案,可能是普通的CSS。
我有一个输入字段。如果被选中,就会出现一个带有一些点击事件的按钮。由于我想保持简单,我使用CSS来隐藏按钮,如果输入不集中。
但是点击从来没有被执行。似乎CSS是在点击之前应用的,所以当onclick被触发时,按钮已经消失了。
有什么办法可以解决这个问题吗?
Array.from(document.getElementsByTagName("button")).forEach(function(button, index) {
button.onclick = function() {
document.getElementsByTagName("input")[index].value = "";
};
});
.hide>input:not(:focus)+button {
display: none;
}
<html>
<body>
<div>
<input type="text" value="working">
<button>Reset</button>
</div>
<div class="hide">
<input type="text" value="not working">
<button>Reset</button>
</div>
</body>
</html>
Array.from(document.getElementsByTagName("button")).forEach(function(button, index) {
button.onclick = function() {
document.getElementsByTagName("input")[index].value = "";
};
});
.hide>input:not(:focus)+button {
display: none;
}
<html>
<body>
<div>
<input type="text" value="working">
<button>Reset</button>
</div>
<div class="hide">
<input type="text" value="not working">
<button onmousedown="return false">Reset</button>
</div>
</body>
</html>
我自己找到了,它和我想象的一样简单。
<button onmousedown="return false">Reset</button>
就像我预想的那样简单:
看来你的假设是对的。它确实看起来像CSS应用在javascript之前。
你可以通过在css属性上添加一个过渡延迟来解决这个问题。display
所以我不得不使用 visibility
而不是。您可以添加 position: absolute;
如果你想让它表现得像 display: none
.
Array.from(document.getElementsByTagName("button")).forEach(function(button, index) {
button.onclick = function() {
document.getElementsByTagName("input")[index].value = "";
};
});
button {
transition: visibility 0.05s;
}
.hide>input:not(:focus)+button {
visibility: hidden;
/*position: absolute; Uncomment to obtain the same effect as display: none*/
}
<html>
<body>
<div>
<input type="text" value="working">
<button>Reset</button>
</div>
<div class="hide">
<input type="text" value="not working">
<button>Reset</button>
</div>
</body>
</html>