通过按钮和JavaScript显示或隐藏div

问题描述 投票:1回答:3

我需要隐藏一个div打开一个网页(显示设置为“无”),但点击按钮必须出现div。我想知道为什么代码工作,直到我将css样式声明到每个div中:如果我将样式块中的css定义到头部(下面注释)并从每个div中删除样式标记,则JavaScript看起来几乎死亡。

<!DOCTYPE html>
<HTML lang="it">
<HEAD>
<TITLE>Prova visualizzazione div via button</TITLE>
<meta charset="UTF-8" />
<script>
	function apriMenu() {
		var idTag;
		idTag = document.getElementById("appari").style;
		if (idTag.display == "none") {
			idTag.display = "block";
			idTag.top = document.getElementById("header").style.height + "px";
		} else if (idTag.display == "block") {
			idTag.display = "none";
		}
	}
</script>
<!-- <style type="text/css">
	header {
		width: 100%;
		background-color: #22ffff;
		height: 40px;
	}
	#appari {
		width: 49%;
		background-color: #ff22ff;
		height: auto;
		display: none;
	}
</style> -->
</HEAD>

<body>
<header id="header" style="width: 100%;
		background-color: #22ffff;
		height: 40px;">
	Questo è l'header<br />
	<div id="side">
		<button onClick="javascript:apriMenu();">Clicca</button>
	</div>
</header>
<div id="appari" style="width: 49%;
		background-color: #ff22ff;
		height: auto;
		display: none;">
	Questo è il div appari
</div>
</body>
</html>
javascript html css onclick
3个回答
3
投票

element.style只获取内联样式,你要找的是computedStyle

所以你需要使用window.getComputedStyle()

查看代码示例:

function apriMenu() {
  var idTag;
  idTag = document.getElementById("appari");
  var displayStyle = window.getComputedStyle(idTag).display;

  if (displayStyle === "none") {
    idTag.style.display = "block";
    idTag.top = document.getElementById("header").style.height + "px";
  } else if (displayStyle === "block") {
    idTag.style.display = "none";
  }
}
header {
  width: 100%;
  background-color: #22ffff;
  height: 40px;
}

#appari {
  width: 49%;
  background-color: #ff22ff;
  height: auto;
  display: none;
}
<header id="header">
  Questo è l'header<br />
  <div id="side">
    <button onClick="javascript:apriMenu();">Clicca</button>
  </div>
</header>
<div id="appari">
  Questo è il div appari
</div>

0
投票

如果没有深入挖掘它,你可以添加一个最后的else语句来显示该元素,如果style.display为空。如果您希望最初显示元素,请使用相反的情况。

function apriMenu() {
    var idTag;
    idTag = document.getElementById("appari").style;
    if (idTag.display == "none") {
        idTag.display = "block";
        idTag.top = document.getElementById("header").style.height + "px";
    } else if (idTag.display == "block") {
        idTag.display = "none";
    }
    else{
        idTag.display = "block";
        idTag.top = document.getElementById("header").style.height + "px";
    }
}

0
投票

这是实现同样事情的另一种更简单的方法:http://next.plnkr.co/edit/ZsAKiwxVA3riRx5Y?open=lib%2Fscript.js

function toggleMenu() {
   var element = document.getElementById("appari");
   element.classList.toggle("showMenu");
}

你基本上只需要打开和关闭一个类来隐藏/显示菜单。我发现使用类这样做很简单。

祝好运!

© www.soinside.com 2019 - 2024. All rights reserved.