18910140161

HTML-尝试从按钮单击显示输入框-JavaScript-Stack溢出

顺晟科技

2022-10-19 12:19:16

69

我对html、css和JS还很陌生。我试图使一个输入字段出现/切换从按钮点击。以下是我到目前为止的代码。

HTML

<form>
            <fieldset>
                <legend>Competency 15 Event Listeners</legend>
                <ol>
                    <li><button type="text" id="theButton" onclick="clickMe()">Click me!</button></li>
                    <li><input type="text" name="popup" id="popup"></li>
                </ol>
            </fieldset>
        </form>

CSS

<form>
            <fieldset>
                <legend>Competency 15 Event Listeners</legend>
                <ol>
                    <li><button type="text" id="theButton" onclick="clickMe()">Click me!</button></li>
                    <li><input type="text" name="popup" id="popup"></li>
                </ol>
            </fieldset>
        </form>

JavaScript

<form>
            <fieldset>
                <legend>Competency 15 Event Listeners</legend>
                <ol>
                    <li><button type="text" id="theButton" onclick="clickMe()">Click me!</button></li>
                    <li><input type="text" name="popup" id="popup"></li>
                </ol>
            </fieldset>
        </form>

我在网上找遍了,似乎找不到答案。提前感谢


顺晟科技:

我建议切换CSS类:

几件事:

  1. 如果button属性的值无效(如这里所示),则该值变为。在表单中,单击按钮刷新页面。因此必须使用不同的类型。

  2. 最初,是因为您使用DOM元素来查找它。DOM解析器没有添加CSS样式表的有关样式的知识。因此,您必须在比较中再包含一个条件-

<form>
            <fieldset>
                <legend>Competency 15 Event Listeners</legend>
                <ol>
                    <li><button type="text" id="theButton" onclick="clickMe()">Click me!</button></li>
                    <li><input type="text" name="popup" id="popup"></li>
                </ol>
            </fieldset>
        </form>

或者,您可以将样式作为内联样式,由DOM解析如下:

<form>
            <fieldset>
                <legend>Competency 15 Event Listeners</legend>
                <ol>
                    <li><button type="text" id="theButton" onclick="clickMe()">Click me!</button></li>
                    <li><input type="text" name="popup" id="popup"></li>
                </ol>
            </fieldset>
        </form>

如果使用字段集,则应将input与type按钮一起使用以生成按钮。我已经将您的按钮更改为带有类型按钮的输入,现在它可以工作了。

还添加了另一个if循环,该循环检查是否存在显示属性,如果该属性为空“”,则将其设置为“none”。如果没有第一个if循环,将需要单击两次才能显示输入,因为首先您需要使用else将display设置为“none”,只有第二次单击将其设置为“block”。

我不记得为什么它会这样工作,但这就是CSS的工作方式,如果您喜欢,可以使用console.log(text.style)获取完整的CSS对象并检查它。

由于定义了初始元素属性viaCSS,因此可能需要使用该方法来获取当前样式

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航