javascript - 通过按钮和 JavaScript 显示或隐藏一个 div

标签 javascript html css onclick

我需要隐藏一个打开网页的 div(显示设置为“无”),但是单击一个按钮必须显示该 div。 在我向每个 div 声明 css 样式之前,我想知道代码为何有效:如果我将样式 block 中的 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>

最佳答案

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>

关于javascript - 通过按钮和 JavaScript 显示或隐藏一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50993080/

相关文章:

javascript - 测试对 overflow-y :auto in browsers 的支持

javascript - Highcharts 条形图工具提示 HTML 定位

javascript - 从工厂获取 JSON 数据

javascript - 通过检查现有的另一个数组来显示数组中的替代图像,该元素是否存在于 angular2 中?

javascript - 使用可选参数对 Where 子句进行后续处理

javascript - Crockford 原型(prototype)继承的小缺点

html - 当较小的屏幕 div 没有拉伸(stretch)时

javascript - 管理鼠标悬停和鼠标单击事件

javascript - 通过 JQuery 检查自动生成的文本字段值

html - 在没有滚动条的情况下一个接一个地显示两个 div 的问题