你想成為iScroll大師。行,這就是我寫以下內(nèi)容的目的。
最好的學(xué)習(xí)iScroll的方法是看示例。在存檔文件中你會發(fā)現(xiàn)一個叫做demo的文件夾示例。這里有大多數(shù)腳本功能的概述。
IScroll是一個類,每個需要使用滾動功能的區(qū)域均要進行初始化。每個頁面上的iScroll實例數(shù)目在設(shè)備的CPU和內(nèi)存能承受的范圍內(nèi)是沒有限制的。
盡可能保持DOM結(jié)構(gòu)的簡潔。iScroll使用硬件合成層但是有一個限制硬件可以處理的元素。
最佳的HTML結(jié)構(gòu)如下:
<div id="wrapper">
<ul>
<li>...</li>
<li>...</li>
...
</ul>
</div>
iScroll作用于滾動區(qū)域的外層。在上面的例子中,UL元素能進行滾動。只有容器元素的第一個子元素能進行滾動,其他子元素完全被忽略。
box-shadow, opacity, text-shadow and alpha channels are all properties that don't go very well together with hardware acceleration. Scrolling might look good with few elements but as soon as your DOM becomes more complex you'll start experiencing lag and jerkiness.
Sometimes a background image to simulate the shadow performs better than box-shadow. The bottom line is: experiment with CSS properties, you'll be surprised by the difference in performance a small CSS change can do.
最基本的腳本初始化的方式如下:
<script type="text/javascript">
var myScroll = new IScroll('#wrapper');
</script>
第一個參數(shù)可以是滾動容器元素的DOM選擇器字符串,也可以是滾動容器元素的引用對象。下面是一個有效的語法:
var wrapper = document.getElementById('wrapper');
var myScroll = new IScroll(wrapper);
所以基本上你要么直接傳遞元素,要么傳遞一個querySelector字符串。因此可以使用css名稱代替ID去選擇一個滾動器容器,如下:
var myScroll = new IScroll('.wrapper');
注意,iScroll使用的是querySelector 而不是 querySelectorAll,所以iScroll只會作用到選擇器選中元素的第一個。如果你需要對多個對象使用iScroll,你需要構(gòu)建自己的循環(huán)機制。
You don't strictly need to assign the instance to a variable (myScroll), but it is handy to keep a reference to the iScroll.
For example you could later check the scroller position or unload unnecessary events when you don't need the iScroll anymore.