如何在jQuery中使用锚元素向上或向下滚动页面
问题是,当我们点击一个本地锚点时,要包含一个滑动效果,并且我们要相应地向上或向下滚动页面。早些时候,我们可以通过使用CSS属性来做到这一点。
语法:
a {
scroll-behavior: smooth;
}
现在在jQuery的帮助下,我们可以通过使用以下两种方法来实现。
- jQuery.offset()方法。这个方法允许我们检索任何元素相对于文档的当前位置。当我们想执行拖放操作或想把新元素定位在另一个现有的元素之上时,这个方法特别有用。
- jQuery.animate()方法。这个方法允许在任何数字的CSS属性上创建动画。要使用该方法,需要有CSS对象。我们可以用这个方法对样式和非样式属性进行动画处理。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to scroll the page up or down
using anchor element in jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
(document).ready(function () {
// Add smooth scrolling to all links
("a").on('click', function (event) {
// Make sure this.hash has a value
// before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor
// click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method
// to add smooth page scroll
// The optional number (800) specifies
// the number of milliseconds it takes
// to scroll to the specified area
('html, body').animate({
scrollTop:(hash).offset().top
}, 500, function () {
// Add hash (#) to URL when done
// scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
<style>
body,
html, .primary {
height: 150%;
}
section {
min-height: 150%;
}
</style>
</head>
<body>
<div>
<a href="#section1">
Click Me to Smooth Scroll
to Section 1 Below
</a>
</div>
<div>
<a href="#section2">
Click Me to Smooth Scroll
to Section 2 Below
</a>
</div>
<div>
<a href="#section3">
Click Me to Smooth Scroll
to Section 3 Below
</a>
</div>
<div class="primary">
<section></section>
</div>
<div class="primary" id="section1">
<section style="background-color:cyan"></section>
</div>
<div class="primary" id="section2">
<section style="background-color:yellow"></section>
</div>
<div class="primary" id="section3">
<section style="background-color:red"></section>
</div>
</body>
</html>
输出:
- 在第1节的滚动效果之前。
- 在第1节的滚动效果后,我们进入青色的方框,如代码所示。