他Stackoverflow,
问题很简单, 如果窗口尺寸小于宽度 960px,我可以单击菜单按钮。 当我点击它时,导航高度将为 325px 而不是 60px,这就是我想要发生的。它可以工作,但是只有第二次单击该按钮才能看到结果。有人可以解释为什么会发生这种情况吗?
// GET DOM
var getdom = (function(){
var DOMstrings = {
menuBtn: '#menu',
navToggle: 'nav',
}
return {
getDOMstrings: function(){
return {
menu: document.querySelector(DOMstrings.menuBtn),
nav: document.querySelector(DOMstrings.navToggle),
}
}
}
})();
// Global Controllor
var global = (function(dom){
var get = dom.getDOMstrings();
function start(){
// MENU NAV HEIGHT
get.menu.addEventListener('click', function(){
console.log('click!');
if(get.nav.style.height === '60px'){
get.nav.style.height = '325px';
}else {
get.nav.style.height = '60px';
}
});
}
return {
init: function(){
start();
}
}
})(getdom);
global.init();
html, body {
margin: 0;
padding: 0;
}
#header {
width: 100%;
height: 150px;
background-color: gray;
}
nav {
width: 100%;
height: 60px;
text-align: center;
font-family: 'Open Sans', sans-serif;
overflow: hidden;
transition: all 1s;
}
#brand {
position: absolute;
font-size: 32px;
left: 10px;
top: 8px;
}
#menu {
position: absolute;
left: 140px;
top: 20px;
display: none;
cursor: pointer;
}
nav ul {
list-style-type: none;
padding-top: 15px;
}
nav ul li {
display: inline;
font-size: 22px;
}
nav ul li a {
text-decoration: none;
color: darkslategray;
border-right: 1px solid black;
padding: 10px 11px;
transition: all 0.5s;
}
.nav-link:hover {
font-size: 24px;
}
#dropdown {
padding-left: 10px;
cursor: pointer;
transition: all 0.5s;
}
@media screen and (max-width: 965px) {
nav {
height: 325px;
}
}
@media screen and (max-width: 960px) {
nav ul li {
display: block;
border-bottom: 1px solid black;
padding-bottom: 10px;
padding-top: 10px;
margin-left: -10%;
}
.margintop {
margin-top: 50px;
}
nav ul li a {
border-right: 0px;
padding: 0px;
}
#dropdown {
padding-left: 0px;
}
}
@media screen and (max-width: 959px){
nav {
height: 60px;
}
#menu {
display: block;
}
}
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Website</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<nav>
<div id="brand">BRAND</div>
<div id="menu">MENU</div>
<ul>
<li class="margintop"><a href="#" class="nav-link">Home</a></li>
<li><a href="#" class='nav-link'>About us</a></li>
<li><a href="#" class='nav-link'>Services</a></li>
<li><a href="#" class='nav-link'>Contact</a></li>
<li id="dropdown" class='nav-link'>More</li>
</ul>
</nav>
<header id="header">
</header>
<script src="app.js"></script>
</html>
最佳答案
您需要使用get.nav.getBoundingClientRect().height
来获取初始高度值。
因此,在这种情况下,您可以将“真实”值(value)与您的积分(325 或 60)进行比较。
正如@squint在评论中提到的,你不能依赖样式的高度属性。尝试使用 getBoundingClientRect
( MDN )。
关于JavaScript 添加事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42179810/