【发布时间】:2020-02-17 15:32:07
【问题描述】:
我目前正在创建一个导航栏,无论鼠标是在导航栏上还是在导航栏外,它都会展开和折叠。我的问题是,当导航栏展开时,我的图标与中心对齐,但我希望它们在导航栏展开之前准确定位在它们所在的位置。我让它们与中心对齐,因为当导航栏折叠时,图标的大小不同并且没有它看起来“不合适”。
let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
sidenav.style.width = "280px";
document.getElementById("expand-icon").classList.add("expand");
document.getElementById("sidenav-expand").style.textAlign = "right";
document.getElementById("sidenav-heading").style.display = "inline-block";
//document.getElementById("links").style.float = "left";
};
sidenav.onmouseout = function() {
sidenav.style.width = "75px";
document.getElementById("expand-icon").classList.remove("expand");
document.getElementById("sidenav-expand").style.textAlign = "center";
document.getElementById("sidenav-heading").style.display = "none";
};
#sidenav {
height: 100%;
width: 75px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #1e1e2d;
overflow-x: hidden;
color: grey;
transition: 0.2s;
}
#sidenav-brand {
padding: 25px 20px;
background-color: #1a1a27;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
}
#sidenav-heading h2 {
margin: 0;
}
#sidenav-expand {
text-align: center;
margin-left: 3px;
}
.expand {
transform: rotate(180deg);
}
#sidenav-links {
margin: 15px 0;
}
#links {
list-style-type: none;
padding: 0;
text-align: center;
}
#links li {
padding: 18px;
display: block;
}
#links li:hover {
color: white;
background-color: hotpink;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Navigation Bar</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script src="https://kit.fontawesome.com/6cc49d804e.js" crossorigin="anonymous"></script>
<script src="js/scripts.js"></script>
</head>
<body>
<div id="sidenav">
<div id="sidenav-brand">
<div id="sidenav-heading" style="display:none;">
<h2>Expanded</h2>
</div>
<div id="sidenav-expand">
<i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
</div>
</div>
<div id="sidenav-links">
<ul id="links">
<li>
<i class="fas fa-id-card fa-2x"></i>
</li>
<li>
<i class="fas fa-graduation-cap fa-2x"></i>
</li>
<li>
<i class="fas fa-briefcase fa-2x"></i>
</li>
<li>
<i class="fas fa-smile-beam fa-2x"></i>
</li>
</ul>
</div>
</div>
</body>
</html>
和 JSFiddle 链接: https://jsfiddle.net/h86zf4d3/
从注释掉的 JS 代码中可以看出,我尝试将图标浮动到左侧,但是,由于某种原因,这消除了列表项的块显示。
【问题讨论】:
-
请不要使用这样的javascript代码来触发鼠标悬停的视觉效果。只需使用
css的:hover选择器
标签: javascript html css