当摘要具有嵌入式文本输入并且用户按下空格键时,如何防止html details元素切换 [英] How to prevent the html details element from toggling when the summary has an embedded text input and user presses space bar
问题描述
我在处于打开状态的details元素的summary标记内输入了文本.目的是捕获用户输入,这些输入最终将显示为详细信息元素(请参见下文).但是,当用户在输入文本时按下空格键时,细节元素会切换.我想防止这种情况.我希望可以通过在keypress事件中使用stopPropagation来完成此操作,但是它似乎无法正常工作.如何防止元素切换?
I have a text input within the summary tag of a details element which is in the open state. The intention is to capture user input which will eventually be displayed as a details element (see below). However the details element toggles when the user presses the space bar while entering text. I want to prevent this. I expected that this could be done using stopPropagation in the keypress event but it does not seem to be working. How do I prevent the element from toggling?
window.onload = function() {
var summary = document.getElementById("x");
var fn = function(e) {
e.stopPropagation();
/*if(e.keyCode == 32){
e.preventDefault();
e.target.value += " "
} */
};
summary.onkeypress = fn;
//summary.onkeydown = fn;
};
<details open>
<summary><input id="x" type="text" /></summary>
Some content
</details>
我需要在React组件中执行此操作,但是为了简单起见,我在这里发布了一个js/html示例.
I need to do this within a React component but I'm posting a js/html example here for simplicity.
一种替代方法是在输入空格时使用preventDefault onkeypress并手动将空格字符连接起来,但这似乎不太合理
One alternative is to use preventDefault onkeypress when space is entered and manually concatenate the space char but this seems inelegant
推荐答案
您可以在 summary
对象上捕获事件,然后 preventDefault()
不会切换详细信息
元素状态,但也不会阻止空间添加.
You can catch the event on summary
object and then preventDefault()
will not toggle details
element state but also will not block space addition.
window.onload = function() {
var summary = document.getElementById("x");
var fn = function(e) {
if(e.keyCode == 32){
e.preventDefault();
}
};
summary.onkeyup = fn;
};
<details open>
<summary id="x"><input type="text" /></summary>
Some content
</details>
请注意,我将 id ="x"
移到了 summary
而不是 input
Pay attention i moved id="x"
to summary
instead of input
这篇关于当摘要具有嵌入式文本输入并且用户按下空格键时,如何防止html details元素切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!