前端入坑纪 09
昨天过生日,零点的今天又是好兄弟过生日,预祝他年年有今日,岁岁有今朝。顺便深夜更新福利来一个,嘿嘿嘿~
一等大事:项目链接
这次换了个源码网址,原来那个runjs网站不知怎么的,一直新建不了,尴尬啊~
HTML 结构
<div class="wrp">
<nav>
<span id="arcr"></span>
<a class="active" href="javascript:;">导航1</a>
<a href="javascript:;">导航2</a>
<a href="javascript:;">导航3</a>
<a href="javascript:;">导航4</a>
<a href="javascript:;">导航5</a>
<a href="javascript:;">导航6</a>
<a href="javascript:;">导航7</a>
<a href="javascript:;">导航8</a>
</nav>
</div>
简单的nav套上a标签,那个span就是滑块
CSS 结构
html,
body {
margin: 0;
padding: 0
}
a {
text-decoration: none;
color: #333;
}
.wrp {
background-color: #fefefe
}
nav {
position: relative;
height: 46px;
line-height: 46px;
text-align: center;
background: #f1eeee;
}
nav a {
position: relative;
display: block;
float: left;
width: 12.5%;
font-size: 13px;
box-sizing: border-box;
}
nav a:hover,
nav a.active {
color: #f7f9c6;
transition: all .15s ease-out;
}
nav a::after {
position: absolute;
right: 0;
display: block;
width: 0;
height: 26px;
top: 10px;
content: "";
}
nav a:last-child::after {
display: none
}
#arcr {
display: block;
width: 12.5%;
height: 46px;
position: absolute;
left: 0;
top: 0;
background-color: #ff5400;
z-index: 0;
transition: all .3s ease-out .2s;
}
nav::after {
content: "";
display: block;
visibility: hidden;
clear: both;
}
滑块是要绝对定位的,相对于它的父级nav,而所有的a都是浮动的,最后nav:after是用来清除浮动的。
JavaScript 结构
var obtn = document.getElementsByTagName('a'),
arc = document.getElementById('arcr'),
winW = window.innerWidth,
obtnLens = obtn.length,
indx = 0;
for (var i = 0; i < obtnLens; i++) {
// 给每个a 增加对应的index,以便后面获取
obtn[i].setAttribute("index", i);
// 给每个a 添加鼠标滑入事件
obtn[i].onmouseenter = function(e) {
// 获取当前滑入的a的index
var idx = e.target.getAttribute("index");
// 去除有active的a标签
document.getElementsByClassName('active')[0].className = "";
// 使用translateX来移动滑块到对应index的a标签上
arc.style.transform ="translateX("+ idx * winW * 0.125 + "px)";
// 对应的a标签 加上active
obtn[idx].className = "active"
}
}
用mouseenter事件是为了更好的演示,小伙伴可以根据实际需求采取更贴切的事件。加油哦,小伙伴们,每天都要进步一点点!