單頁式網站常見的整屏翻頁效果,在這裡用最精簡的做法實作:以 CSS transform 移動整個容器,再靠 jQuery 統一處理滾輪、鍵盤與右側圓點三種輸入方式,並 automatically 適配不同螢幕尺寸。
https://hovertree.com/texiao/jquery/69/
所有 section 垂直堆疊成一個長條,外層 .section-wrap 用 translateY 往上推。頁面索引 i 決定要推到哪裡,於是只需替容器加上 put-section-0 到 put-section-4 其中一個類別,CSS 就接手完成 1 秒的位移動畫。標題的淡入也是同一個機制:目前所在的那一屏,其 .title 會被加上 active,內含的 .tit 便從下方 25px 浮上並轉為不透明。
.section-wrap {
width: 100%; height: 100%;
overflow: visible;
transition: transform 1s cubic-bezier(0.86, 0, 0.03, 1);
-webkit-transition: -webkit-transform 1s cubic-bezier(0.86, 0, 0.03, 1);
}
.section-wrap .section { position: relative; width: 100%; height: 100%; }
.section-wrap .section .title p { padding: 0 4%; opacity: 0; }
.section-wrap .section .title.active .tit {
opacity: 1;
transform: translateY(-25px);
transition: all 2s cubic-bezier(0.86, 0, 0.8, 1);
}
.put-section-0 { transform: translateY(0); }
.put-section-1 { transform: translateY(-100%); }
.put-section-2 { transform: translateY(-200%); }
.put-section-3 { transform: translateY(-300%); }
.put-section-4 { transform: translateY(-400%); }
<section class="section-wrap">
<div class="section section-1">
<div class="title active"><p class="tit">CSS3 縱向滾屏翻頁</p></div>
</div>
<div class="section section-2">
<div class="title"><p class="tit">第二屏內容</p></div>
</div>
<!-- 更多 section -->
</section>
<ul class="section-btn">
<li class="on"></li>
<li></li>
<li></li>
</ul>
<div class="arrow">«</div>
$(function(){
var i = 0;
var $btn = $('.section-btn li'),
$wrap = $('.section-wrap'),
$arrow = $('.arrow');
function up() { i++; if (i == $btn.length) i = 0; }
function down() { i--; if (i < 0) i = $btn.length - 1; }
function run(){
$btn.eq(i).addClass('on').siblings().removeClass('on');
$wrap.attr("class", "section-wrap")
.addClass("put-section-" + i)
.find('.section').eq(i).find('.title').addClass('active');
}
// 右側圓點
$btn.each(function(index){
$(this).click(function(){ i = index; run(); });
});
// 下方箭頭
$arrow.one('click', go);
function go(){ up(); run(); setTimeout(function(){ $arrow.one('click', go); }, 1000); }
// 滑鼠滾輪(需搭配 mousewheel 插件)
$wrap.one('mousewheel', mouse_);
function mouse_(event){
event.deltaY < 0 ? up() : down();
run();
setTimeout(function(){ $wrap.one('mousewheel', mouse_); }, 1000);
}
// 鍵盤上下鍵
$(document).one('keydown', k);
function k(event){
var key = event.keyCode || event.which;
if (key === 38) { down(); run(); }
if (key === 40) { up(); run(); }
setTimeout(function(){ $(document).one('keydown', k); }, 1000);
}
});
三種輸入都綁成一次性的 one(),並在 1 秒後重新綁定,等於在動畫播放期間鎖住觸發。少了這層保護,一次長滾輪滾動就可能觸發好幾次翻頁,畫面會跳過好幾屏。這是滾屏類效果最容易被忽略、卻最影響手感的細節。
適用瀏覽器:360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗;不支援 IE8 及以下版本。
來源:何問起