gpt4 book ai didi

Javascript : why i have to click 2 times to run the function?

转载 作者:行者123 更新时间:2023-11-30 19:45:41 25 4
gpt4 key购买 nike

window.onload = function(){
var about2 = document.getElementById("about");
about2.addEventListener("click",about);

}

function about(){
var divabout = document.getElementById("aboutme");
if(divabout.style.display == "none"){
divabout.style.display = "flex";
divabout.style.justifyContent ="center";
}else{
divabout.style.display ="none";
}
}

请告诉我为什么我必须单击两次才能运行此功能的原因。以及如何修复请。非常感谢 。我刚刚在 css 中为 1 个 div 标签设置了 display:none,我想更改显示属性。

最佳答案

因为默认情况下您没有为 HTML 设置任何显示属性。这就是为什么在第一次点击时 javascript 会设置它需要的一切。然后从第二次点击开始工作。

这是你的代码,你没有在 html 中添加样式

    <div id="about">Hello</div>    <div id="aboutme">About Me</div>

And Here if I fix/add this style="display:flex;justify-content: center;" in your about me like this

    <div id="about">Hello</div>    <div id="aboutme" style="display:flex;justify-content: center;">About Me</div>

Now you can check you need only one click to run

window.onload = function() {
var about2 = document.getElementById("about");
about2.addEventListener("click", about);

}

function about() {
var divabout = document.getElementById("aboutme");
if (divabout.style.display == "none") {
divabout.style.display = "flex";
divabout.style.justifyContent = "center";

} else {
divabout.style.display = "none";

}
}
<div id="about">Hello</div>
<div id="aboutme" style="display:flex;justify-content: center;">OK About Me</div>

关于Javascript : why i have to click 2 times to run the function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54970888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com