考虑以下代码:
<form id='f' style='display: none'>
<input type='text' id='style'/>
</form>
<button onclick='document.getElementById("f").style.display = "block"'>Click</button>
在点击按钮后,我希望表单变得可见,但它不是。为什么呢?
请注意,如果以下条件之一为真,它将按预期工作:
输入输入id未命名为"style"
发布于 2018-12-17 04:39:29
表单中的控件元素也会成为表单元素的属性。因此,通过使用style
作为其id,可以使<form>
的style
属性引用一个输入。
如果添加console.log(document.getElementById('f').style)
,它将返回<input id="style">
,而不是元素的预期样式规则
我会将窗体包装在一个容器中,并将内联样式应用于该容器。很少会使用<form>
作为块元素
<div id="f" style='display: none'>
<form>
<input type='text' id='style' />
</form>
</div>
<button onclick='document.getElementById("f").style.display = "block"'>Click</button>
发布于 2018-12-17 04:42:57
这是因为通过在子元素中使用' id =' style‘,您将创建对该子元素的引用,而不是访问父元素的样式,以便修复您应该为id使用不同的名称。
示例:https://jsfiddle.net/kwz3v9fx/2/
<form id='f' style='display: none'>
<input type='text' id='anotherName'/>
</form>
<button onclick='document.getElementById("f").style.display = "block"'>Click</button>
发布于 2018-12-17 04:52:15
这是因为内联样式(style="display: none;"
)优先于内部样式(document.getElementById("f").style.display = "block"
)。要解决此问题,请改用setAttribute
:
<form id='f' style='display: none'>
<input type='text' id='style'/>
</form>
<button onclick='document.getElementById("f").setAttribute("style", "display: block;")'>Click</button>
您可以看到这是因为<form>
元素在JavaScript中被视为对象,并且当子元素具有name
或id
属性时,该属性将作为属性添加到form
对象。请看下面的代码片段:
console.log(document.getElementById("f").style);
/*This shows the <input> element rather than the styles
applied to the actual <form> element*/
<form id="f">
<input type="text" id="style" />
</form>
https://stackoverflow.com/questions/53806208
复制相似问题