jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。翻屏(通常指页面滚动效果)是网页设计中的一种常见效果,可以通过 jQuery 来实现。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 平滑滚动示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
}
#section1 { background-color: #f06; }
#section2 { background-color: #0f6; }
#section3 { background-color: #06f; }
</style>
</head>
<body>
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
<div id="section1" class="section">Section 1</div>
<div id="section2" class="section">Section 2</div>
<div id="section3" class="section">Section 3</div>
<script>
$('a[href^="#"]').on('click', function(event) {
var target = $(this.getAttribute('href'));
if( target.length ) {
event.preventDefault();
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 视差滚动示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
margin: 0;
perspective: 1px;
transform-style: preserve-3d;
}
.parallax {
position: relative;
height: 100vh;
overflow-x: hidden;
transform-style: preserve-3d;
}
.layer {
position: absolute;
width: 100%;
height: 100%;
transform: translateZ(-1px) scale(2);
}
.bg {
background-size: cover;
background-position: center;
}
#layer1 { background-image: url('image1.jpg'); }
#layer2 { background-image: url('image2.jpg'); }
</style>
</head>
<body>
<div class="parallax">
<div id="layer1" class="layer bg"></div>
<div id="layer2" class="layer bg"></div>
</div>
<script>
$(window).on('scroll', function() {
var scrollTop = $(this).scrollTop();
$('.layer').css('top', scrollTop * 0.5);
});
</script>
</body>
</html>
function throttle(func, wait) {
let timeout = null;
return function() {
const context = this;
const args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args);
}, wait);
}
};
}
$(window).on('scroll', throttle(function() {
// 处理滚动事件
}, 200));
$(window).scrollTop()
和 $(element).offset().top
来精确计算。var scrollTop = $(window).scrollTop();
var elementTop = $('#element').offset().top;
if (scrollTop >= elementTop) {
// 元素进入视口
}
通过以上方法,可以有效地实现和优化 jQuery 翻屏效果。
领取专属 10元无门槛券
手把手带您无忧上云