<ul class="hearder-1st nav-underline">
<li data-nav="iot-product">IoT Products </li>
<li data-nav="cameras">AI Cameras </li>
<li data-nav="solution">Solutions</li>
<li data-nav="Customers">
<a href="/company/success-stories/">Success Stories</a>
</li>
<li data-nav="support">Support</li>
<li data-nav="partners">Partners</li>
<li data-nav="company">Company</li>
</ul>
// 下划线元素
.nav-underline {
&__line {
position: absolute;
bottom: 0;
left: 0;
height: 3px;
background: $main-blue;
border-radius: 1px;
transition: all 0.3s cubic-bezier(0.42, 0.01, 0.59, 0.99);
pointer-events: none;
z-index: 10;
opacity: 0; // 默认隐藏
width: 0;
&.active {
opacity: 1;
width: 100%; // 或由JS动态设置宽度
}
}
}
let $nav = $('.nav-underline')
let $items = $nav.find('li')
let $line = $('<div class="nav-underline__line"></div>')
$nav.append($line)
// 默认隐藏下划线
$line.css({
opacity: 0,
width: 0
})
// 下划线移动到指定元素并显示
function moveLineTo($el) {
if (!$el || $el.length === 0) return
let navOffset = $nav.offset().left
let elOffset = $el.offset().left
let elWidth = $el.outerWidth()
$line.css({
width: elWidth,
left: elOffset - navOffset,
opacity: 1
})
}
// 下划线隐藏
function hideLine() {
$line.css({
opacity: 0,
width: 0
})
}
// 悬停时移动并显示下划线
$items.on('mouseenter focus', function () {
moveLineTo($(this))
})
// 鼠标移出导航栏
$nav.on('mouseleave', function () {
let $active = $items.filter('.active')
if ($active.length) {
moveLineTo($active)
} else {
hideLine()
}
})
// 只保留这一处点击事件
$items.on('click', function () {
let $this = $(this)
let nav = $this.data('nav')
if ($this.hasClass('active')) {
$this.removeClass('active')
$(`.nav-content[data-nav="${nav}"]`).removeClass('active')
hideLine()
} else {
$this.addClass('active').siblings().removeClass('active')
$(`.nav-content[data-nav="${nav}"]`).addClass('active').siblings().removeClass('active')
moveLineTo($this)
}
})
// 初始状态:如果有active项则显示,否则隐藏
let $active = $items.filter('.active')
if ($active.length) {
moveLineTo($active)
} else {
hideLine()
}