鼠标略过白色方框选项时,为每一个选项添加与头部导航栏相同的背景颜色,同时设置字体颜色为白色;尽可能与图片效果保持一致。功能要求:①鼠标略出头像及白色方框区域时,白色方框消失;②头像右侧显示存储在本地存储中的用户名称,③点击退出登录,清除在本地存储中的数据并跳转到登陆页面。
时间: 2024-05-05 19:17:40 浏览: 170
以下是实现该功能的代码示例:
HTML代码:
```html
<header>
<div class="logo"></div>
<div class="user">
<div class="avatar"></div>
<div class="username"></div>
<div class="options">
<div class="option">选项1</div>
<div class="option">选项2</div>
<div class="option">选项3</div>
<div class="option">选项4</div>
<div class="logout">退出登录</div>
</div>
</div>
</header>
```
CSS代码:
```css
header {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #f7f7f7;
padding: 20px;
}
.logo {
width: 50px;
height: 50px;
background-image: url("logo.png");
background-size: cover;
background-position: center;
}
.user {
display: flex;
align-items: center;
position: relative;
}
.avatar {
width: 40px;
height: 40px;
background-image: url("avatar.png");
background-size: cover;
background-position: center;
border-radius: 50%;
cursor: pointer;
}
.username {
margin-left: 10px;
font-size: 16px;
font-weight: bold;
}
.options {
display: none;
position: absolute;
top: 50px;
right: 0;
width: 150px;
background-color: #f7f7f7;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
z-index: 999;
}
.option {
padding: 10px;
cursor: pointer;
}
.option:hover {
background-color: #007bff;
color: #fff;
}
.logout {
padding: 10px;
cursor: pointer;
background-color: #dc3545;
color: #fff;
}
.logout:hover {
background-color: #c82333;
}
```
JavaScript代码:
```javascript
// 获取相关元素
const avatar = document.querySelector(".avatar");
const options = document.querySelector(".options");
const optionList = document.querySelectorAll(".option");
const logout = document.querySelector(".logout");
const username = document.querySelector(".username");
// 鼠标移入头像时显示选项菜单
avatar.addEventListener("mouseover", function() {
options.style.display = "block";
});
// 鼠标移出头像和选项菜单时隐藏选项菜单
avatar.addEventListener("mouseout", function() {
options.style.display = "none";
});
options.addEventListener("mouseover", function() {
options.style.display = "block";
});
options.addEventListener("mouseout", function() {
options.style.display = "none";
});
// 鼠标移入选项时改变背景颜色和字体颜色
optionList.forEach(function(option) {
option.addEventListener("mouseover", function() {
option.style.backgroundColor = "#007bff";
option.style.color = "#fff";
});
option.addEventListener("mouseout", function() {
option.style.backgroundColor = "transparent";
option.style.color = "#000";
});
});
// 点击退出登录时清除本地存储并跳转到登录页面
logout.addEventListener("click", function() {
localStorage.clear();
window.location.href = "login.html";
});
// 从本地存储中获取用户名并显示
const storedUsername = localStorage.getItem("username");
if (storedUsername) {
username.textContent = storedUsername;
}
```
阅读全文