繁体   English   中英

getElementById()。style.display不起作用

[英]getElementById().style.display does not work

我为<div>制作了一些js代码来显示或消失。

[src.js]

openSearch = () => {
    var con = document.getElementById("search-bar");
    if(con.style.display == 'none') {
        con.style.display = 'block';
    } else {
        con.style.display = 'none';
    }
}

[style.css中]

#search-bar {
    position: absolute;
    height: 4em;
    width: 20em;
    background-color: white;
    border: 1px solid black;
    padding: 1.5rem;
    right: 0;
    display: none;
}

并将onclick="openSearch()"<a>标记。

第一次单击<a>标记时,它没有任何作用。

但是再次单击,它可以正常工作。

所以我试图console.log(document.getElementById(“ search-bar”)。style.display,它抛出“”(空白)。

我不知道,我定义display: nonesearch-bar ,但为什么最初的style.display search-bar是空白的价值?

我该如何解决?

或者,您可以将显示样式移至另一个类并可以切换类。

 openSearch = () => { var con = document.getElementById("search-bar"); con.classList.toggle("hidden"); } 
 #search-bar { position: absolute; height: 4em; width: 20em; background-color: white; border: 1px solid black; padding: 1.5rem; right: 0; } .hidden { display: none; } 
  <a onclick="openSearch()">Toggle</a> <div id="search-bar" class="hidden">Some text here</div> 

function openSearch()
 {
       var div = document.getElementById("search-bar");
       if (div.style.display !== "none") {
          div.style.display = "none";
        }
      else {
         div.style.display = "block";
       }
 }

您可以尝试通过js将样式初始化为无:

document.getElementById("search-bar").style.display = 'none';

页面加载时。 我的猜测是可以的。

[解决了]

首先,我添加display: none到css文件。

但是在对标签使用style="display: none" ,它可以正常工作。

也许我认为有加载优先级,但是我不知道为什么。

当您在CSS中设置display:none ,它像display=""一样是单调的。 而不display=none 结果是相同的,但是如果您选择display='none'他将返回false。您可以这样尝试:

openSearch = () => {
    var con = document.getElementById("search-bar");
    if(con.style.display == '') {
        con.style.display = 'block';
    } else {
        con.style.display = '';
    }
}

它会很好地工作

使用此行代码:

if(con.style.display == 'none' || con.style.display == '') {

 openSearch = () => { var con = document.getElementById("search-bar"); if(con.style.display == 'none' || con.style.display == '') { con.style.display = 'block'; } else { con.style.display = 'none'; } } 
 #search-bar { position: absolute; height: 4em; width: 20em; background-color: white; border: 1px solid black; padding: 1.5rem; right: 0; display: none; } 
 <div id="search-bar">My Div</div> <a onclick="openSearch()" href="#">Click</a> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM