jQuery 平滑滚动链接颜色更改不起作用可能是由于多种原因造成的。以下是一些基础概念、可能的原因以及解决方案:
!important
来确保你的样式规则不会被其他规则覆盖:!important
来确保你的样式规则不会被其他规则覆盖:以下是一个完整的示例,展示了如何实现平滑滚动并更改链接颜色:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Smooth Scroll Example</title>
<style>
body {
height: 2000px; /* Just for demonstration */
}
a[href^="#"] {
color: red;
}
a[href^="#"]:hover {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<a href="#section1">Go to Section 1</a>
<div id="section1" style="margin-top: 1000px;">Section 1</div>
<script>
$(document).ready(function() {
$('a[href^="#"]').on('click', function(event) {
event.preventDefault();
var target = $(this.hash);
$('html, body').animate({
scrollTop: target.offset().top
}, 800, function() {
window.location.hash = this.hash;
$(this).css('color', 'green'); // 更改颜色
}.bind(this));
});
});
</script>
</body>
</html>
在这个示例中,当用户点击链接并滚动到指定部分时,链接的颜色会变为绿色。确保你的代码逻辑与此类似,并根据需要进行调整。
领取专属 10元无门槛券
手把手带您无忧上云