【问题标题】:classList.add( ) and classList.add( ) is not working properly [duplicate]classList.add() 和 classList.add() 无法正常工作 [重复]
【发布时间】:2021-11-06 18:48:41
【问题描述】:

因此,当用户单击按钮时,我希望第一部分消失,而第二部分显示。这里发生的事情就像是一闪而过。第一部分只是隐藏了一秒钟,第二部分也是如此。请看代码我的代码:)

HTML

 <style>
        .hide{
            display: none;
        }
 </style>


 <section id="first">
            <form>
                <label for="p1Name">PLAYER ONE</label>
                <input type="text" id="p1Name" placeholder="TYPE PLAYER NAME">
                <label class="label" for="p2Name">PLAYER TWO</label>
                <input type="text" id="p2Name" placeholder="TYPE PLAYER NAME">
                <button id="start">START</button>
            </form>
        </section>
        <section id="second" class="hide">
            <h1>HELLO, WORLD!!!</h1>
        </section>

Javascript

const button = document.querySelector("#start");
const firstPage = document.querySelector("#first");
const secondPage = document.querySelector("#second");

    button.addEventListener('click', ()=>{
        firstPage.classList.add("hide");
        secondPage.classList.remove("hide");
        console.log("work");       
    })

【问题讨论】:

  • &lt;button&gt; 的默认操作是提交它的子表单。使用表单的submit 事件来更改可见性停止该提交。或者将按钮的类型更改为“仅”一个按钮 -> type="button"

标签: javascript html css


【解决方案1】:

按钮的默认类型是提交,因此当点击按钮时表单正在提交。您可以将按钮的类型显式设置为 button,也可以使用 preventDefault() 阻止 click 事件处理函数内部的事件留在页面上。

const button = document.querySelector("#start");
const firstPage = document.querySelector("#first");
const secondPage = document.querySelector("#second");

button.addEventListener('click', (e)=>{
    firstPage.classList.add("hide");
    secondPage.classList.remove("hide");
    console.log("work");
    e.preventDefault();
})
<style>
.hide{
    display: none;
}
</style>


<section id="first">
    <form>
        <label for="p1Name">PLAYER ONE</label>
        <input type="text" id="p1Name" placeholder="TYPE PLAYER NAME">
        <label class="label" for="p2Name">PLAYER TWO</label>
        <input type="text" id="p2Name" placeholder="TYPE PLAYER NAME">
        <button id="start">START</button>
    </form>
</section>
<section id="second" class="hide">
    <h1>HELLO, WORLD!!!</h1>
</section>

【讨论】:

  • 实际上有数千个(或多或少好)重复...
  • 为什么CSS部分有文字?为什么 HTML 部分中有 &lt;style&gt; 元素?
猜你喜欢
  • 2022-11-18
  • 1970-01-01
  • 2017-07-15
  • 2015-09-06
  • 2016-05-06
  • 2016-05-12
  • 2018-07-19
  • 2018-10-21
  • 1970-01-01
相关资源
最近更新 更多