웹 프론트엔드 HTML 튜토리얼 HTML5应用开发:JavaScript库iScroll教程_html/css_WEB-ITnose

HTML5应用开发:JavaScript库iScroll教程_html/css_WEB-ITnose

Jun 24, 2016 am 11:39 AM

目录

1. iScroll介绍

2. 安装和使用

3. 简单的iScroll例子

4. Pinch & Zoom

5. Snap to element

6. iScroll 详细参数

1. iScroll介绍

一般我们在开发传统Web网站时,偶尔会用固定某一区域的宽度/高,然后借用设置这一区域的overflow:scroll,使得其里面超过该区域范围的内容,可以通过移动滚动条来查看。

而在iOS(iOS5以下)的mobile Safari以及Android的浏览器当中,原生不支持页面内任意区域的overflow:scroll这个属性。传统的做法是使用绝对定位的Header以及Footer,然后让整个页面内容可以滚动。iScroll的出现,也是用Javascript来模拟CSS的overflow:scroll属性,解决页面内元素的滚动问题。

由于iScroll本身使用了transform3d的属性来模拟滚动效果,使得它性能上也非常不错,因为这个属性能使用平台提供的硬件加速。在实际使用当中,效果平滑流畅,可以与原生的相媲美。

本文示例代码可以从GitHub下载,地址:https://github.com/cubiq/iscroll。

2. 安装和使用

iScroll的安装非常简单,你只需要从Github下载最新版本,iScroll是一个纯JS库,因此你可以像使用其他JS脚本一样用script标签来包含iScroll.js, 其并不依赖于jQuery或者其他的库文件:

 

3. 简单的iScroll例子

本例中,将一步一步地一个通过iScroll模板来实现一个Native App样式的List View。

第一步,在HTML网页中,添加iScroll.js

第二步,在页面加载完成之后,实例化iScroll,loaded函数,典型代码如下:

 

 

1

 

myScroll是一个全局变量,你可以在任何地方使用scroller函数。当DOMContentLoaded触发之后即加载load函数,但是有的时候由于DOM加载需要一段时间,同时加载iScroll的内容可能会导致页面异常,可以为load函数添加一个settimeout,代码如下:

 

 

1

 

第三步,添加HTML元素,本例中,元素包括header,footer,和wrapper(List滚动区域),代码如下:

 

[xhtml]

  • Pretty row 1
  • Pretty row 2
  • Pretty row 3
  • Pretty row 4
  • Pretty row 5
  • Pretty row 6
  • Pretty row 7
[/xhtml]

#wrapper是显示的窗口,# scroller是包含所有list的集合,一般来说scroller比wrapper要大,scroller在wapper中滚动,只有在wapper中的元素才被显示出来。默认情况下,iScroller只会滚动在#wrapper下的第一个元素,如果你有多个元素都需要滚动,请按照下列方式填写:

 

[xhtml]

  • ... ...
  • ... ...
[/xhtml]

第四步,添加样式表CSS:

我们需要header和footer固定,所以他们的样式如下:

 

[xhtml]#header { position:absolute; z-index:2; top:0; left:0; width:100%; height:45px; line-height:45px; background-image:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0, #fe96c9), color-stop(0.05, #d51875), color-stop(1, #7b0a2e)); background-image:-moz-linear-gradient(top, #fe96c9, #d51875 5%, #7b0a2e); background-image:-o-linear-gradient(top, #fe96c9, #d51875 5%, #7b0a2e); padding:0; color:#eee; font-size:20px; text-align:center; } #footer { position:absolute; z-index:2; bottom:0; left:0; width:100%; height:48px; background-color:#222; background-image:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0, #999), color-stop(0.02, #666), color-stop(1, #222)); background-image:-moz-linear-gradient(top, #999, #666 2%, #222); background-image:-o-linear-gradient(top, #999, #666 2%, #222); padding:0; border-top:1px solid #444; } [/xhtml]

Wrapper区域在header和footer之间,其各元素样式表如下:

 

[xhtml]#wrapper { position:absolute; z-index:1; top:45px; bottom:48px; left:0; width:100%; background:#aaa; overflow:auto; } #scroller { position:absolute; z-index:1; /* -webkit-touch-callout:none;*/ -webkit-tap-highlight-color:rgba(0,0,0,0); width:100%; padding:0; } #scroller ul { list-style:none; padding:0; margin:0; width:100%; text-align:left; } #scroller li { padding:0 10px; height:40px; line-height:40px; border-bottom:1px solid #ccc; border-top:1px solid #fff; font-size:14px; } [/xhtml]

至此,一个完整的listView形式Web App已经完成,可以在: 这里 观看效果。 完整代码如下:

 

[xhtml]

iScroll demo: Check DOM Changes
  • Pretty row 1
  • Pretty row 2
  • Pretty row 3
  • Pretty row 4
  • Pretty row 5
  • Pretty row 6
  • Pretty row 7
[/xhtml]

 

4. Pinch & Zoom

如果单纯的滚动不能满足应用的需求,list元素不仅需要可以滚动,而且可以进行放大和缩小,iSroll同样提供了Pinch & Zoom的方式。你所需要做的工作只是在Scroller声明的时候添加zoom参数。

var myScroll = new iScroll('wrapper', { zoom: true });

参数zoomMax是指最大允许放大的倍数,默认值是4,用户可以自行定义。

如果想要获得更加流畅的图片放大缩小滚动的效果,推荐使用CSS样式的硬件加速性能,为所有会被缩放的图像添加以下选项:-webkit-transform:translate3d(0,0,0)即可。请注意,使用到硬件加速性能会消耗更多的计算资源,可能导致程序崩溃。

完整demo代码:

 

[xhtml]

iScroll demo: zoom

iscrollLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

iscrollAt vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.

[/xhtml]

 

5. Snap to element

使用snap选项可以在固定的位置之间来回滚动list,类似跑马灯的效果。实现snap效果同样是在iScroll声明的时候添加相应参数,代码如下:

 

 

1 var myScroll = new iScroll('wrapper', { snap: true, momentum: false, hScrollbar: false, vScrollbar: false });

 

完整demo代码:

 

[xhtml]

iScroll demo: Snap to element
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
  • cell
[/xhtml]

6. iScroll详细参数:

hScroll, 用来锁定水平滚动,默认情况下,水平和垂直滚动都是支持的。如果被设定为false,则不能水平方向滚动.

vScroll, 用来锁定垂直滚动

hScrollbar, 水平的滚动条是否显示选项。.

vScrollbar, 垂直的滚动条是否显示选项.

bounce, enable/disable 当滚动超出范围时,是否有弹跳动画。.

momentum, enable/disable inertia. Default: true. 如果想要节省计算资源,可以设置为false.

lockDirection, 当元素在一个方向滚动时(如水平),另一个方向(如垂直)的滚动会被锁定.

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

& lt; Progress & Gt의 목적은 무엇입니까? 요소? & lt; Progress & Gt의 목적은 무엇입니까? 요소? Mar 21, 2025 pm 12:34 PM

이 기사는 HTML & lt; Progress & Gt에 대해 설명합니다. 요소, 그 목적, 스타일 및 & lt; meter & gt의 차이; 요소. 주요 초점은 & lt; progress & gt; 작업 완료 및 & lt; meter & gt; Stati의 경우

HTML은 초보자를 위해 쉽게 배우나요? HTML은 초보자를 위해 쉽게 배우나요? Apr 07, 2025 am 12:11 AM

HTML은 간단하고 배우기 쉽고 결과를 빠르게 볼 수 있기 때문에 초보자에게 적합합니다. 1) HTML의 학습 곡선은 매끄럽고 시작하기 쉽습니다. 2) 기본 태그를 마스터하여 웹 페이지를 만들기 시작하십시오. 3) 유연성이 높고 CSS 및 JavaScript와 함께 사용할 수 있습니다. 4) 풍부한 학습 리소스와 현대 도구는 학습 과정을 지원합니다.

& lt; datalist & gt의 목적은 무엇입니까? 요소? & lt; datalist & gt의 목적은 무엇입니까? 요소? Mar 21, 2025 pm 12:33 PM

이 기사는 HTML & LT; Datalist & GT에 대해 논의합니다. 자동 완성 제안을 제공하고, 사용자 경험을 향상시키고, 오류를 줄임으로써 양식을 향상시키는 요소. 문자 수 : 159

& lt; meter & gt의 목적은 무엇입니까? 요소? & lt; meter & gt의 목적은 무엇입니까? 요소? Mar 21, 2025 pm 12:35 PM

이 기사는 HTML & lt; meter & gt에 대해 설명합니다. 범위 내에 스칼라 또는 분수 값을 표시하는 데 사용되는 요소 및 웹 개발의 일반적인 응용 프로그램. & lt; meter & gt; & lt; Progress & Gt; 그리고 Ex

뷰포트 메타 태그는 무엇입니까? 반응 형 디자인에 중요한 이유는 무엇입니까? 뷰포트 메타 태그는 무엇입니까? 반응 형 디자인에 중요한 이유는 무엇입니까? Mar 20, 2025 pm 05:56 PM

이 기사는 모바일 장치의 반응 형 웹 디자인에 필수적인 Viewport Meta Tag에 대해 설명합니다. 적절한 사용이 최적의 컨텐츠 스케일링 및 사용자 상호 작용을 보장하는 방법을 설명하는 반면, 오용은 설계 및 접근성 문제로 이어질 수 있습니다.

& lt; iframe & gt; 꼬리표? 보안을 사용할 때 보안 고려 사항은 무엇입니까? & lt; iframe & gt; 꼬리표? 보안을 사용할 때 보안 고려 사항은 무엇입니까? Mar 20, 2025 pm 06:05 PM

이 기사는 & lt; iframe & gt; 외부 컨텐츠를 웹 페이지, 공통 용도, 보안 위험 및 객체 태그 및 API와 같은 대안을 포함시키는 태그의 목적.

HTML, CSS 및 JavaScript의 역할 : 핵심 책임 HTML, CSS 및 JavaScript의 역할 : 핵심 책임 Apr 08, 2025 pm 07:05 PM

HTML은 웹 구조를 정의하고 CSS는 스타일과 레이아웃을 담당하며 JavaScript는 동적 상호 작용을 제공합니다. 세 사람은 웹 개발에서 의무를 수행하고 화려한 웹 사이트를 공동으로 구축합니다.

HTML의 시작 태그의 예는 무엇입니까? HTML의 시작 태그의 예는 무엇입니까? Apr 06, 2025 am 12:04 AM

anexampleStartingtaginhtmlis, whithbeginsaparagraph.startingtagsareessentialinhtmlastheyinitiate rements, definetheirtypes, andarecrucialforstructurituringwebpages 및 smanstlingthedom.

See all articles