li下划线跟随鼠标移动

	<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()
	}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值