用”-webkit-overflow-scrolling: touch”讓你的mobile web application支援momentum-based scrolling
通常在mobile web application的開發時,第一個在實際mobile device上遇到的問題就是使用者scroll時覺得卡卡的,這時候只要在可scroll的元素上加上-webkit-overflow-scrolling: touch;
即可解決。
範例:
Element {
overflow: auto;
-webkit-overflow-scrolling: touch;
}
-webkit-overflow-scrolling
這個CSS property提供了兩個值:auto
及touch
,它決定可scroll元素是否支援momentum-based scrolling
,iOS的網頁上預設支援momentum-based scrolling,但是我們因為實作上的需求將結構設為多層結構可scroll元素為fixed height時,momentum-based scrolling就會失效。
例如:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Without momentum-based-scrolling</title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<style>
html, body {
margin: 0;
padding: 0;
}
body {
width: 100vw;
height: 100vh;
}
#app {
width: 100%;
height: 100%;
overflow: auto;
}
.long-div {
width: 100%;
height: 1200px;
background: repeating-linear-gradient(red, yellow 10%, green 20%);
}
</style>
</head>
<body>
<div id='app'>
<div class="long-div"></div>
</div>
</body>
</html>
無論將#app
的height設為absolute value或relative value,因為直接指定了這個元素的height,所以導致momentum-based scrolling失效
但若是#app
的height沒被設定或是設為auto
,momentum-based scrolling仍有效:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>With momentum-based-scrolling</title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<style>
html, body {
margin: 0;
padding: 0;
}
body {
width: 100vw;
height: 100vh;
}
#app {
width: 100%;
overflow: auto;
}
.long-div {
width: 100%;
height: 1200px;
background: repeating-linear-gradient(red, yellow 10%, green 20%);
}
</style>
</head>
<body>
<div id='app'>
<div class="long-div"></div>
</div>
</body>
</html>
什麼是momentum-based scrolling?
當使用者的滑動手勢結束、手指離開螢幕後,網頁內容仍然會根據使用者滑動時的速度、力道繼續滑動並隨時間停止。
一般使用網頁上的scrollbar或滾動滑鼠滾輪時,當滾動的動作一結束,頁面滾動會立即停止在滾動動作停止的位置,但是在mobile上,為了給使用者更加良好的使用體驗,momentum-based scrolling的implement是必要的。
-webkit-overflow-scrolling
的兩個值就分別代表了支援/不支援momentum-based scrolling:
auto
:不支援momentum-based scrolling,當使用者結束滑動手勢、手指離開螢幕之後,頁面滾動立即停止。
touch
:支援momentum-based scrolling,當使用者結束滑動手勢、手指離開螢幕之後,頁面滾動仍然會持續一下子,依據使用者滑動的速度及力道漸漸停止。