- Getting Started with jQuery Mobile
- link Create a Basic Page Template
- link Add Content
- link Make a Listview
- link Add a Slider
- link Make a Button
- link Choose a Theme Swatch
- link Go Forth and Build Something
- A Touch-Optimized Web Framework
- Download jQuery Mobile
- Developer Links
- Seriously cross-platform with HTML5
- Theming: Built to be branded
- Download builder: Customize for speed
- Введение в jQuery Mobile
- Ключевые особенности
- Поддерживаемые платформы
- Страницы
- Page Title
- Page Footer
- Foo
- Page Footer
- Bar
- Page Footer
Getting Started with jQuery Mobile
jQuery Mobile provides a set of touch-friendly UI widgets and an Ajax-powered navigation system to support animated page transitions. This guide will show you how you can build your first jQuery Mobile application.
link Create a Basic Page Template
To get started, you can simply paste the template below in your favorite text editor, save, and open the document in a browser.
In the of this template, a meta viewport tag sets the screen width to the pixel width of the device. References to jQuery, jQuery Mobile, and the mobile theme stylesheet from the CDN add all the styles and scripts. jQuery Mobile 1.4 works with versions of jQuery core 1.8 and newer.
In the , a div with a data-role of page is the wrapper used to delineate a page. A header bar ( data-role=»header» ), a content region ( role=»main» >) and a footer bar ( data-role=»footer» ) are added inside to create a basic page (all three are optional). These data- attributes are HTML5 attributes used throughout jQuery Mobile to transform basic markup into an enhanced and styled widget.
html>
html>
head>
title>My Page title>
meta name="viewport" content="width=device-width, initial-scale=1">
link rel="stylesheet" href="https://code.jquery.com/mobile/[version]/jquery.mobile-[version].min.css">
script src="https://code.jquery.com/jquery-[version].min.js"> script>
script src="https://code.jquery.com/mobile/[version]/jquery.mobile-[version].min.js"> script>
head>
body>
div data-role="page">
div data-role="header">
h1>My Title h1>
div>
div role="main" class="ui-content">
p>Hello world p>
div>
div data-role="footer">
h4>My Footer h4>
div>
div>
body>
html>
link Add Content
The next step is to add content inside the content container. Any standard HTML elements – headings, lists, paragraphs, etc. can be added. You can write your own custom styles to create custom layouts by adding an additional stylesheet to the after the jQuery Mobile stylesheet.
link Make a Listview
jQuery Mobile includes a diverse set of common listviews that are coded as lists with a data-role=»listview» added. Here is a simple linked list that has a role of listview . The data-inset=»true» attribute makes the listview look like an inset module, while data-filter=»true» adds a dynamic search filter.
ul data-role="listview" data-inset="true" data-filter="true">
li>a href="#">Acura a> li>
li>a href="#">Audi a> li>
li>a href="#">BMW a> li>
li>a href="#">Cadillac a> li>
li>a href="#">Ferrari a> li>
ul>
link Add a Slider
The framework contains a full set of form elements that are automatically enhanced into touch-friendly styled widgets. Here’s a slider made with the new HTML5 input type of range, no data-role needed. All form elements must always be properly associated with a and the group of form elements be wrapped in a tag.
form>
label for="slider-0">Input slider: label>
input type="range" name="slider" id="slider-0" value="25" min="0" max="100" />
form>
link Make a Button
There are a few ways to make buttons. A common one is to turn a link into a button so it’s easy to click. Just start with a link and add a data-role=»button» attribute to it. You can add an icon with the data-icon attribute and optionally set its position with the data-iconpos attribute.
a href="#" data-role="button" data-icon="star">Star button a>
link Choose a Theme Swatch
jQuery Mobile has a robust theme framework that supports up to 26 sets of toolbar, content, and button colors, called a «swatch». You can add a data-theme=»b» attribute to any of the widgets on this page: page, header, list, input for the slider, or button to turn it a dark shade of grey. Different swatch letters from a-b in the default theme can be used to mix and match swatches.
If you add the theme swatch to the page, all the widgets inside the content will automatically inherit the theme.
a href="#" data-role="button" data-icon="star" data-theme="a">Button a>
If you would like to create a custom theme, you can use ThemeRoller that allows users to create their own theme through an easy to use drag and drop interface. You will then be able to download and use your newly created theme.
link Go Forth and Build Something
This guide has provided you with a basic structure for a jQuery Mobile page and a few enhanced elements. You can explore the full jQuery Mobile API Documentation and jQuery Mobile Demo Center to learn about linking pages, adding animated page transitions, and creating dialogs and popups.
If you’re more of the type who prefers actually writing JavaScript to build your apps, and you don’t want to use the data- attribute configuration system, you can take full control of everything and call plugins directly as these are all standard jQuery plugins built with the UI widget factory. Particularly useful information for such cases can be found in the global configuration, events, and methods sections.
Finally, you can read up on scripting pages, generating dynamic pages, and building PhoneGap apps.
A Touch-Optimized Web Framework
jQuery Mobile is a HTML5-based user interface system designed to make responsive web sites and apps that are accessible on all smartphone, tablet and desktop devices.
Download jQuery Mobile
Developer Links
Seriously cross-platform with HTML5
jQuery Mobile framework takes the «write less, do more» mantra to the next level: Instead of writing unique applications for each mobile device or OS, the jQuery mobile framework allows you to design a single highly-branded responsive web site or application that will work on all popular smartphone, tablet, and desktop platforms.
Theming: Built to be branded
We believe that your web site or app should feel like your brand, not any particular OS. To make building highly customized themes easy, we’ve created ThemeRoller for Mobile to make it easy to drag and drop colors and download a custom theme. For polished visuals without the bloat, we leverage CSS3 properties like text-shadow and box-shadow .
Download builder: Customize for speed
We recommend using our tool to build a custom bundle that contains only the components you need. The builder generates a custom JavaScript file, as well as full and structure-only stylesheets for production use.
Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath
Введение в jQuery Mobile
Мобильная стратегия jQuery может быть легко объяснена — это внедрение пользовательского JavaScript в наиболее часто используемые браузеры на мобильных платформах.
Основной ценностью нашего подхода является широкий спектр платформ, поддерживаемых jQuery Mobile. Мы прилагаем все усилия, что бы jQuery поддерживал все мобильные браузеры, по крайней мере занимающие номинальную долю рынка.
Что бы обеспечить широкую поддержку, все страницы в jQuery Mobile построены на чистом HTML, это обеспечивает совместимость с довольно многими web-ориентированными устройствами. В устройствах, которые интерпретируют CSS и JavaScript, jQuery Mobile применяет прогрессивные методы, что бы ненавязчиво преобразовать семантические страницы используя богатый интерактивный опыт и мощь Query и CSS. Стандарты доступности активных интернет-приложений, таких как WAI-ARIA тесно интегрированы во всей структуре для оказания поддержки для чтения с экрана.
Ключевые особенности
- Построенный на JQuery знакомый синтаксис
- Совместимость со всеми основными мобильными платформами — iOS, Android, Blackberry, Palm WebOS, Nokia/Symbian, Windows Mobile, bada, MeeGo и с базовой поддержкой всех устройств которые понимают HTML
- Небольшой размер файла (12кб включающий функциональность для всех мобильных) и минимальная зависимость от изображений для увеличения скорости
- HTML5 разметка управляемая конфигурацией страниц и минимальные требования для быстрого развития сценариев
- Прогрессивный подход, усиление основного содержания и функциональность всех мобильных, электронных книжек, Desktop Platform, будет легко использоваться на новых мобильных платформах.
- Автоматическая инициализация с помощью HTML5 date-role атрибутов в разметке HTML, автоматически инициализирует все JQuery Mobile виджеты найденные на странице.
- Стандарты доступности активных интернет-приложений, таких как WAI-ARIA включены что бы обеспечить удобное чтение с экрана (например VoiceOver в IOS) и других вспомогательных технологий.
- Простое API, рационализирующее процесс поддержки Touch, мыши, и других видов устройств ввода.
- Новые модули расширяющие возможности сенсорного управления.
- Мощные темы визуализации приложения делают весьма простым построение интерфейсов.
Поддерживаемые платформы
- Apple iOS: iPhone, iPod Touch, iPad (все версии)
- Android: все устройства (все версии)
- Blackberry Torch (version 6)
- Palm WebOS Pre, Pixi
- Nokia N900 (в разработке)
Страницы
В jQuery Mobile входит автоматическая загрузка страниц с помощью AJAX, с включенной кнопкой возврата, настройки анимации и простые инструменты для отображения диалогов. Цель этой модели, позволить разработчикам создавать веб-сайты с использованием передовой практики — где обычные ссылки будут работать без какой-либо специальной настройки, при этом создавая нативные приложения, чего нельзя было бы достигнуть используя стандартный HTML.
Мобильная структура страницы.
jQuery Mobile сайт должен начинаться с ‘DOCTYPE’ HTML5, что бы в полной мере использовать особенности фрэймворка. (Старые устройства и браузеры, которые не понимают HTML5, будут благополучно игнорировать doctype и различные особые атрибуты). В заголовке head, указываются ссылки к jQuery, jQuery Mobile, теме Mobile CSS и другие необходимые компоненты.
Внутри тэга body, каждое представление или страница на мобильном устройстве определяется элементом (обычно это div) с атрибутом data-role=«page».
В пределах контейнера «page» может быть использован любой валидный HTML код, где непосредственными потомками «page» должны быть блоки div с атрибутами «header», «content», и «footer».
Законченный шаблон простой страницы
Page Title
Page content goes here.
Page Footer
Внешние страницы, содержащие ссылку
JQuery Mobile автоматизирует процесс создания Ajax сайтов и приложений. По умолчанию, при нажатии на ссылку, указывающую на внешнюю страницу (например, products.html), структура разбирает HREF ссылки, формулирует запрос Ajax и отображает загрузку. Если запрос Ajax успешно выполнен, новое содержание страницы будет добавлено в DOM, все мобильные виджеты автоматически инициализируются, и новая страница будет выведена на экран. Если запрос Ajax не удался, отдельным слоем, будет выведено сообщение об ошибке, которое исчезнет после через небольшой промежуток времени, так, что это не нарушит навигационный поток.
Ссылки внутри страницы
Единый документ HTML может содержать несколько страниц, которые загружаются путем укладки нескольких div элементов с атрибутами data-role=«pages». Каждая страница должна иметь уникальный идентификатор, который будет использоваться для связи между внутренними блоками с помощью HREF=»#Foo». При нажатии на ссылку, будет происходить поиск внутренней страницы (page) с нужным ID и вывод этого блока на экран. Важно отметить, что если вы связываете страницу, которая была загружена через Ajax со страницей с несколькими внутренними страницами, необходимо добавить REL = «external» к ссылке. Это говорит фрэймворку полностью перегрузить страницу и очистить хэш в URL. Это важно потому, что Ajax страницы используют решетки (#) для отслеживания истории, а внутристраничные ссылки используют хэш внутри своих страниц, это может вызвать конфликты. Например, ссылка на страницу, содержащую несколько внутренних страниц будет выглядеть следующим образом:
Вот пример двух страниц сайта построенных с помощью div, навигация которых завязана на id этих элементов. Заметим, что идентификаторы на странице нужны только для поддержки внутренней связи страниц, и не являются обязательными, если каждая страница отдельный документ HTML. Вот две страницы внутри body элемента:
Foo
I'm first in the source order so I'm shown as the page.
View internal page called bar
Page Footer
Bar
I'm first in the source order so I'm shown as the page.
Back to foo
Page Footer
ПОЖАЛУЙСТА, ОБРАТИТЕ ВНИМАНИЕ: Так как мы используем хэш-навигацию для отслеживания истории для всех страниц, в настоящее время невозможно осуществленияе ссылок типа якорь (index.html # Foo). Источник http://jquerymobile.com/demos/1.0a2/