利用构造函数 写的 导航特效
导航移动变化特效(两种特效)-构造函数–codepen.io
一个构造函数 NavSlide
普通效果
伸长拉伸效果
- 原理:
- 利用 offset系列API(注意要配合定位使用,详情见HTML DOM offsetLeft 属性-菜鸟教程 注意其
注意: offsetParent 元素是一个指向最近的(指包含层级上的最近)包含该元素的定位元素或者最近的元素。
) - html结构
div#navContainer > nav > ul > li > a
另外 div.moveShadow
作为阴影块 - div#navContainer 相对定位 ,div.moveShadow绝对定位
- 根据鼠标移入的目标元素的
offsetLeft
,与当前阴影的offsetLeft
的差值(可为正负)判断左右移动方向
JS源码(html-css在下方codepen链接中)
function NavSlide(_contianName) {
this.NavSlide = document.querySelector(_contianName)
this.moveShadow = document.querySelector(`${_contianName} .moveShadow`)
this.navUl = document.querySelector(`${_contianName} nav>ul`)
this.navItemList = document.querySelectorAll(`${_contianName} nav>ul>li`)
const _navThis = this
this.hoverEffect = function(){
for(let i=0;i<_navThis.navItemList.length;i++){
this.navItemList[i].addEventListener('mouseenter',function(){
_navThis.navItemList[i].classList.add('liActive')
_navThis.navItemList[i].firstChild.classList.add('currentItem')
})
this.navItemList[i].addEventListener('mouseleave',function(){
_navThis.navItemList[i].classList.remove('liActive')
_navThis.navItemList[i].firstChild.classList.remove('currentItem')
})
}
}
this.stretchEffect = function(){
console.log('hi');
const moveShadow = _navThis.moveShadow
moveShadow.style.width = _navThis.navItemList[0].offsetWidth + 'px'
moveShadow.style.left = _navThis.navItemList[0].offsetLeft + 'px'
for(let i=0;i<_navThis.navItemList.length;i++){
const item = _navThis.navItemList[i]
item.addEventListener('mouseenter',function(e){
for(let i=0;i<_navThis.navItemList.length;i++){
_navThis.navItemList[i].childNodes[0].classList.remove("currentItem")
}
let overItem = e.target
if(overItem.offsetLeft - moveShadow.offsetLeft >0 ){
moveShadow.style.width = (overItem.offsetLeft+overItem.offsetWidth-moveShadow.offsetLeft) + 'px'
setTimeout(()=>{
moveShadow.style.width = overItem.offsetWidth + 'px'
moveShadow.style.left = overItem.offsetLeft + 'px'
},200)
}else{
moveShadow.style.left = overItem.offsetLeft + 'px'
moveShadow.style.width = (moveShadow.offsetLeft+moveShadow.offsetWidth-overItem.offsetLeft) + 'px'
setTimeout(()=>{
moveShadow.style.width = overItem.offsetWidth + 'px'
},200)
}
})
item.firstElementChild.addEventListener('mouseenter',function(e){
e.target.classList.add('currentItem')
})
}
}
}
let newNav = new NavSlide('#navContain1')
newNav.stretchEffect()
导航移动变化特效(两种特效)-构造函数–codepen.io