普通的导航大家都会做,像这种穿透字体的导航应该很少见吧。高亮不是通过单独设置一个active类来设置字体高亮颜色,鼠标滑过导航项,字体可以部分是黑色,不分是白色,这种效果的实现
感兴趣的可以关注下我的系列课程【webApp之h5端实战】,里面有大量的css3动画效果制作原生知识分析,讲解,该系列还在不断更新中。
实现效果
代码实现
- html内容结构
<ul id="ul1">
<li class="box">首页</li>
<li class="box">新闻</li>
<li class="box">图片</li>
<li class="box">视频</li>
<li id="mark">
<ul id="ul2">
<li class="box">首页</li>
<li class="box">新闻</li>
<li class="box">图片</li>
<li class="box">视频</li>
</ul>
</li>
</ul>
- UI美化
* {
margin: 0;
padding: 0;
}
#ul1 {
width: 428px;
height: 30px;
margin: 30px auto;
position: relative;
}
ul{
list-style: none;
}
#ul1 li {
float: left;
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
background-color: red;
margin-right: 5px;
cursor: pointer;
}
#ul1 #mark {
position: absolute;
left: 0;
top: 0;
overflow: hidden;
/* background-color: green; */
z-index: 3
}
#ul2{
position: absolute;
width: 428px;
left: -1px;
top:-1px;
color:#fff;
}
- 核心代码逻辑
const oUl = document.getElementById('ul1')
const oMask = document.getElementById('mark')
const aLi = oUl.getElementsByTagName('li')
const oUl2 = document.getElementById('ul2')
let iTimer = null,
iTimer2 = null
let iSpeed = 0
aLi[0].classList.add('active')
for (let index = 0; index < aLi.length; index++) {
const item = aLi[index]
item.onmouseover = function () {
clearTimeout(iTimer2)
startMove(this.offsetLeft)
}
item.onmouseout = function () {
iTimer2 = setTimeout(() => {
startMove(0)
}, 100)
}
}
oMask.onmouseover = function () {
clearTimeout(iTimer2) // 鼠标移动到oMask方块时,停止oMask方块的移动,让它保持在当前位置
}
oMask.onmouseout = function () {
iTimer2 = setTimeout(() => {
startMove(0)
}, 100)
}
function startMove(iTarget) {
clearInterval(iTimer)
iTimer = setInterval(function () {
iSpeed += (iTarget - oMask.offsetLeft) / 6
iSpeed *= 0.75
if (
Math.abs(iSpeed) <= 1 &&
Math.abs(iTarget - oMask.offsetLeft) <= 1
) {
clearInterval(iTimer)
oMask.style.left = iTarget + 'px'
oUl2.style.left = -iTarget + 'px'
iSpeed = 0
} else {
oMask.style.left = oMask.offsetLeft + iSpeed + 'px'
oUl2.style.left = -oMask.offsetLeft + 'px'
}
}, 30)
}
这样,我们就实现了一个创意的导航