Tips for mobile phone development: JavaScript and CSS function code sharing

Source: Internet
Author: User
Tags repetition

1. Viewport:

The visible area. For the desktop browser, we all know exactly what viewport is, and that is to go out all the toolbars, the status bar, the scroll bar, and so on to look at the page area,
This is a truly effective area. Because the mobile device screen width is different from the traditional web, we need to change the viewport;

There are actually 4 properties that we can manipulate:

The code is as follows:
Width-//viewport (range from 200 to 10,000, default is 980 pixels)
Height-//viewport (range from 223 to 10,000)

Initial-scale-//Initial zoom ratio (range from >0 to 10)

Minimum-scale-//allows the user to zoom to the minimum scale
Maximum-scale-//allows the user to zoom to the maximum scale

User-scalable-//whether the user can manually shrink (no,yes)


So how do these settings make safari aware? In fact, it's very simple, just a meta, shaped like:

The code is as follows:
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">//Coding
<meta id= "viewport" name= "viewport" content= "width=320; initial-scale=1.0;maximum-scale=1.0; User-scalable=no; " />
<meta name= "apple-mobile-web-app-capable" content= "yes"/>//Another technique for offline applications
<meta name= "Apple-mobile-web-app-status-bar-style" Content=black "/>//Hide status bar
<meta content= "Black" name= "Apple-mobile-web-app-status-bar-style"/>//The style of the status bar on safari top in the specified iphone
<meta content= "Telephone=no" name= "format-detection"/>//tell the device to ignore numbers in the page as phone numbers
<meta name= "Author" contect= "mr.he"/>


After setting up the initial-scale=1, we can finally make the page design at a rate of 1:1. Another important concept about viewport is that the iphone's Safari browser has no scroll bar at all, and it's not a simple "hide scroll bar", and there is no such feature at all. The iphone's Safari browser actually displays the page completely from the beginning, and then uses viewport to see a portion of it. When you drag with your finger, you actually drag the page instead of the viewport. The browser behavior changes more than the scroll bar, and the interaction event is not the same as the normal desktop.

2. Link:

The code is as follows:
<link rel= "Apple-touch-startup-image" href= "startup.png"/>//settings Start Page picture
<link rel= "Apple-touch-icon" href= "iphon_tetris_icon.png"/>//You can display good-looking icons when setting bookmarks
<link rel= "stylesheet" media= "All and (orientation:portrait)" href= "portrait.css" >//Portrait mode style
<link rel= "stylesheet" media= "All and (Orientation:landscape)" href= "landscape.css"//Landscape mode style

Style used when vertical screen
<style media= "All and (orientation:portrait)" type= "Text/css" >
#landscape {display:none;}
</style>

Styles used when traversing a screen
<style media= "All and (Orientation:landscape)" type= "Text/css" >
#portrait {display:none;}
</style>

3. Event:

The code is as follows:
Gesture Events
Touchstart//triggers when finger touches the screen
Touchmove//triggers when a finger that has touched the screen begins to move
Touchend//triggers when the finger leaves the screen
Touchcancel

Touch events
Gesturestart//triggered when two fingers touch the screen
Gesturechange//Triggers when two fingers start moving after touching the screen
Gestureend

Screen Rotation events
Onorientationchange

Detects when a touch screen finger changes direction
Orientationchange

Related properties supported by the touch event
Touches
Targettouches
Changedtouches
ClientX//X coordinate of touch relative to the viewport (excludes scroll offset)
ClientY//Y coordinate of touch relative to the viewport (excludes scroll offset)
ScreenX//Relative to the screen
ScreenY//Relative to the screen
PageX//Relative to the full page (includes scrolling)
Pagey//Relative to the full page (includes scrolling)
Target/Node The touch event originated from
Identifier//An identifying number, unique to each touch event

4. Screen Rotation event: Onorientationchange
Add a screen rotation event to listen to the screen rotation status (left, right, or not) at any time. Example:

The code is as follows:
Determine if the screen is rotated
function Orientationchange () {
Switch (window.orientation) {
Case 0:
Alert ("Portrait mode 0,screen-width:" + Screen.width + "; Screen-height: "+ screen.height);
Break
CASE-90:
Alert ("left-handed -90,screen-width:" + Screen.width + "; Screen-height: "+ screen.height);
Break
Case 90:
Alert ("Right-handed 90,screen-width:" + Screen.width + "; Screen-height: "+ screen.height);
Break
Case 180:
Alert ("Landscape mode 180,screen-width:" + Screen.width + "; Screen-height: "+ screen.height);
Break
};<br>};
Add Event Listener
AddEventListener (' Load ', function () {
Orientationchange ();
Window.onorientationchange = Orientationchange;
});

5. Hide the Address bar & when handling events, prevent the scroll bar from appearing:

The code is as follows:
Hide the Address bar & prevent scroll bars from appearing when handling events
AddEventListener (' Load ', function () {
SetTimeout (function () {window.scrollto (0, 1);}, 100);
});

6. Two-hand finger swipe event:

The code is as follows:
Two-hand finger swipe event
AddEventListener (' Load ', function () {window.onmousewheel = Twofingerscroll;},
False//compatible with each browser, indicating that the event handler is called during the bubbling phase (true capture phase)
);
function Twofingerscroll (EV) {
var delta =ev.wheeldelta/120; Determine the delta value (for example, plus or minus) and then perform the appropriate action
return true;
};


7. Determine if it is an iphone:

The code is as follows:
Determine if the IPhone:
function Isapplemobile () {
Return (navigator.platform.indexOf (' IPad ')! =-1);
};

8. Localstorage:

Example: (Note data name N to enclose in quotation marks)

The code is as follows:
var v = localstorage.getitem (' n ')?   Localstorage.getitem (' n '): ""; If the data with the name n is present, it is read out and given the variable v.
Localstorage.setitem (' n ', v); Writes data with a name of N and a value of V
Localstorage.removeitem (' n '); Delete data with name N


9. Use special Links:
If you turn off auto-recognition and want some phone numbers to link to your iPhone's dialing capabilities, you can use this to declare a phone link,

The code is as follows:
<a href= "tel:12345654321" > Call me </a>
<a href= "sms:12345654321" > Texting </a>


Or for cells:

The code is as follows:
&LT;TD onclick= "location.href= ' tel:122 '" >

10. Automatic capitalization and auto-correction
To turn these two features off, you can use the Autocapitalize and AutoCorrect options:

The code is as follows:
<input type= "text" autocapitalize= "Off" autocorrect= "off"/>

One. WebKit CSS:
① "box Model" specifically describes the nature of the bounding box block content, including boundaries, padding, and so on.

The code is as follows:
-webkit-border-bottom-left-radius:radius;
-webkit-border-top-left-radius:horizontal_radius Vertical_radius;
-webkit-border-radius:radius; Container fillet
-webkit-box-sizing:sizing_model; Border constant Value: Border-box/content-box
-webkit-box-shadow:hoff voff blur color; Container Shadows (Parameters are: horizontal x-direction offset; vertical y-direction offset; Gaussian blur radius value; shadow color value)
-webkit-margin-bottom-collapse:collapse_behavior; Constant value: collapse/discard/separate
-webkit-margin-start:width;
-webkit-padding-start:width;
-webkit-border-image:url (borderimg.gif) Round/stretch Round/stretch;
-webkit-appearance:push-button; Built-in CSS performance, temporarily only support push-button


The ② "visual formatting Model" describes the nature of the block elements that determine the location and size.

The code is as follows:
Direction:rtl
Unicode-bidi:bidi-override; Constant: Bidi-override/embed/normal


③ "Visual Effects" describes properties that adjust the visual effects of block content, including overflow behavior, adjustment behavior, visibility, animation, transformations, and transitions.

The code is as follows:
Clip:rect (10px, 5px, 10px, 5px)
Resize:auto; Constant: auto/both/horizontal/none/vertical
visibility:visible; Constant: collapse/hidden/visible
-webkit-transition:opacity 1s linear; Animation effect Ease/linear/ease-in/ease-out/ease-in-out
-webkit-backface-visibility:visibler; Constants: Visible (Default)/hidden
-webkit-box-reflect:right 1px; Mirror reversal
-webkit-box-reflect:below 4px-webkit-gradient (linear, left top, left bottom,
From (Transparent), color-stop (0.5, transparent), to (white));
-webkit-mask-image:-webkit-gradient (linear, left top, left bottom, from (Rgba (0,0,0,1)), to (Rgba (0,0,0,0))); CSS Matte/Mask effects
-webkit-mask-attachment:fixed; Constant: Fixed/scroll
-webkit-perspective:value; Constant: None (default)
-webkit-perspective-origin:left top;
-webkit-transform:rotate (5DEG);
-webkit-transform-style:preserve-3d; Constant: flat/preserve-3d; (2D and 3D)


④ "generated content, AutoNumber, and List" describes the properties that allow you to change the content of a component, create an auto-numbered chapter and title, and manipulate the content of the style list.

The code is as follows:
Content: "Item" Counter (section) "";
This resets the counter.
First section
>two section
Three section
Counter-increment:section 1;
Counter-reset:section;


⑤ "Paging Media" describes performance and appearance properties that control the behavior of a printed version of a webpage, such as a page break.

The code is as follows:
Page-break-after:auto; Constant: Always/auto/avoid/left/right
Page-break-before:auto; Constant: Always/auto/avoid/left/right
Page-break-inside:auto; Constant: Auto/avoid


⑥ the "color and Background" Description property controls the component of the text content of block-level elements and colors under the background.

The code is as follows:
-webkit-background-clip:content; Constant: Border/content/padding/text
-webkit-background-origin:padding; Constant: Border/content/padding/text
-webkit-background-size:55px; Constant: length/length_x/length_y


⑦ "Font" is a factor in the selection of text fonts that specifically describe the nature of the font. The report also describes the properties used to download the font definition.

The code is as follows:
Unicode-range:u+00-ff, u+980-9ff;


⑧ "Text" describes the specific text style, spacing, and automatic scrolling of properties.

The code is as follows:
Text-shadow: #00FFFC 10px 10px 5px;
Text-transform:capitalize; Constant: Capitalize/lowercase/none/uppercase
Word-wrap:break-word; Constant: Break-word/normal
-webkit-marquee:right large infinite normal 10s; Constant: direction (direction) increment (iteration count) repetition (repetition) style (style) speed (velocity);
-webkit-marquee-direction:ahead/auto/backwards/down/forwards/left/reverse/right/up
-webkit-marquee-incrementt:1-n/infinite (infinite Times)
-webkit-marquee-speed:fast/normal/slow
-webkit-marquee-style:alternate/none/scroll/slide
-webkit-text-fill-color: #ff6600; Constants: Capitalize, lowercase, none, uppercase
-webkit-text-security:circle; Constant: Circle/disc/none/square
-webkit-text-size-adjust:none; Constant: Auto/none;
-webkit-text-stroke:15px #fff;
-webkit-line-break:after-white-space; Constant: Normal/after-white-space
-webkit-appearance:caps-lock-indicator;
-webkit-nbsp-mode:space; Constant: Normal/space
-webkit-rtl-ordering:logical; Constant: visual/logical
-webkit-user-drag:element; Constant: Element/auto/none
-webkit-user-modify:read-only; Constant: Read-write-plaintext-only/read-write/read-only
-webkit-user-select:text; Constant: Text/auto/none


⑨ the details of the layout and design performance table described in "table".

The code is as follows:
-webkit-border-horizontal-spacing:2px;
-webkit-border-vertical-spacing:2px;
-webkit-column-break-after:right; Constant: Always/auto/avoid/left/right
-webkit-column-break-before:right; Constant: Always/auto/avoid/left/right
–webkit-column-break-inside:logical; Constant: Avoid/auto
-webkit-column-count:3; Sub-column
-webkit-column-rule:1px solid #fff;
Style:dashed,dotted,double,groove,hidden,inset,none,outset,ridge,solid


⑩ "User Interface" describes attributes that involve user interface elements in the browser, such as scrolling text area, scroll bar, and so on. The report also describes attributes that are outside the scope of the page content, such as the cursor's callout style and display when you hold down touch touch
Target, such as a link on the iphone.

The code is as follows:
-WEBKIT-BOX-ALIGN:BASELINE,CENTER,END,START,STRETCH constant: Baseline/center/end/start/stretch
-webkit-box-direction:normal; constant: Normal/reverse
-webkit-box-flex:flex_valuet
-webkit-box-flex-group:group_number
-webkit-box-lines:multiple; Constant: Multiple/single
-webkit-box-ordinal-group:group_number
-webkit-box-orient:block-axis; Constant: Block-axis/horizontal/inline-axis/vertical/orientation
–webkit-box-pack:alignment; Constant: Center/end/justify/start

12. Animation transitions
This is the most innovative feature in Webkit: Defining animations using transition functions.

The code is as follows:
-webkit-animation:title infinite ease-in-out 3s;
Animation has these properties:
-webkit-animation-name://attribute name, which is the keyframes we define
-webkit-animation-duration:3s//Duration
-webkit-animation-timing-function://Transition type: Ease/linear (linear)/ease-in (slow to fast)/ease-out (fast to slow)/ease-in-out (slow to fast to slow) Cubic-bezier
-WEBKIT-ANIMATION-DELAY:10MS//Animation delay (default 0)
-webkit-animation-iteration-count://Number of cycles (default 1), Infinite for Infinity
-webkit-animation-direction://Animation mode: Normal (default forward playback), alternate (alternate direction, first and second forward playback, odd number of reverse playback)


These can also be abbreviated. But what really makes me feel good is that keyframes, which can define an animation's transition process for invocation, is 0% to 100% or from (0%) through to (100%). Simply put, as long as you have an idea, it is easy for you to make the element change in the way it is in the process.

The code is as follows:
-webkit-transform: Type (zoom scale/rotation rotate/Tilt skew/displacement translate)
Scale (num,num) magnification. ScaleX and ScaleY (3), can be abbreviated as: scale (*, *)
Rotate (*deg) rotation angle. Rotatex and Rotatey, can be abbreviated as: rotate (*, *)
Skew (*deg) tilt angle. Skewx and Skewy, can be abbreviated as: Skew (*, *)
Translate (*,*) coordinates move. TranslateX and Translatey, can be abbreviated as: translate (*, *).


Examples of implementing a mock popup message box (Alert):
① defining transitions (described keyframes in <style type= "Text/css" > Segment):

The code is as follows:
@-webkit-keyframes Divzoom
{
0% {-webkit-transform:scale (0.01)}
60% {-webkit-transform:scale (1.05)}
80% {-webkit-transform:scale (0.95)}
100% {-webkit-transform:scale (1.00)}
}
. szoom {-webkit-animation:divzoom 0.5s ease-in-out}


(It's easy to see that the elements are 0.01 times times smaller--small but not 0 times times, magnified to 1.05 times times, scaled down to 0.95 times times, and then to 1 time times the normal size.) The entire transition process event is 0.5 seconds, animated in ease-in-out, i.e. slow to fast and slow, with only 1 transitions by default. This is exactly what you often see in the IPhone popup with the animated effect of the cue message! )
② defining elements (in <body> section):

The code is as follows:
<div id= "Layerh" style= "-WEBKIT-BORDER-RADIUS:12PX; border:2px solid #FFF;-webkit-box-shadow:0px 2px 4px #888;p osition:absolute; left:24px; top:106px;<br>width:256px; height:268px; padding-left:8px; Padding-right:8px;color: #FFFFFF; text-shadow:1px 1px 1px #000; Text-align:center;
Background-image:url (' bg-msg.png '); Background-repeat:no-repeat;
Z-index:1; Visibility:hidden; ">
<p><span style= "FONT-SIZE:16PT; Font-weight:bold "> Instructions for use </span></p>
&LT;HR noshade size= "1" >
<div id= "HelpText" style= "height:120px" > Explanatory text </div>
&LT;HR noshade size= "1" >
<form name= "FORMV" method= "POST" >
<input type= "button" value= "Confirm" name= "B1"
Style= "width:100%; height:40px; font-size:14pt; Ont-weight:bold;
Color: #FFFFFF; text-shadow:0px-1px 1px #000; "
onclick= "layerh.style.visibility= ' hidden '" >
</form>
</div>


③ Start animation (in JavaScript-defined functions)

The code is as follows:
function Phelp ()
{
layerH.style.visibility = ' Visible '
LayerH.style.cssText = "-webkit-animation-delay:" + math.random () + "MS"
Layerh.classname = ' Szoom '
}


(This startup function is well understood.) But why use the-webkit-animation-delay sentence? Because when an element transitions display is complete, the next time you cannot animate the transition, if its style does not change. We have cleverly used its animation delay time definition to make it change, avoiding the above problems. Where the random number function math.random () is used to produce a random number greater than 0 less than 1. Of course, the user is not aware of the delay of fraction milliseconds. )

Add:

1. Lock viewport

The code is as follows:
Ontouchmove= "Event.preventdefault ()"//Lock viewport, any screen operation does not move the user interface (except for the pop-up keyboard).

2. The appearance of the clicked element changes, you can use the style to set:

The code is as follows:
-webkit-tap-highlight-color: Color


3. Detecting Iphone/ipod
To develop a mobile website for a particular device, the first thing to do is to detect the device. Here is the UA that detects iphone/ipod using JavaScript and then turns to the exclusive URL.

The code is as follows:
if ((Navigator.userAgent.match (/iphone/i)) | | (Navigator.userAgent.match (/ipod/i))) {
if (Document.cookie.indexOf ("iphone_redirect=false") = = =-1) {
window.location = "http://m.example.com";
}
}


Although JavaScript can be run on a fruit device, the user can still disable it. It also causes client refreshes and additional data transfers, so here's the server-side detection and steering:

The code is as follows:
if (strstr ($_server[' http_user_agent '), ' IPhone ') | | strstr ($_server[' http_user_agent '], ' iPod ')) {
Header (' Location:http://yoursite.com/iphone ');
Exit ();
}


4. Prevent automatic font resizing when rotating the screen

The code is as follows:
HTML, body, form, fieldset, p, Div, H1, H2, H3, H4, H5, h6 {-webkit-text-size-adjust:none;}


5. The iphone only recognizes the CSS
If you do not want device detection, you can use CSS media queries to define styles specifically for iphone/ipod.

The code is as follows:
@media screen and (max-device-width:480px) {}


6. Reduce the picture
The larger image of the site is usually more than 480 pixels wide, and if you use the previous code to limit the zoom, the images will obviously exceed the screen in the iphone version. Fortunately for the iphone, we can use CSS to let the iphone automatically zoom out the big picture.

The code is as follows:
@media screen and (max-device-width:480px) {
Img{max-width:100%;height:auto;}
}


7. Simulation: hover pseudo-Class
There is no hover event because the iphone does not have a mouse pointer. Then the Css:hover pseudo-class is useless. But the iphone has a touch event, ontouchstart similar to onmouseover,ontouchend similar to onmouseout. So we can use it to simulate hover. Using javascript:

The code is as follows:
var mylinks = document.getElementsByTagName (' a ');
for (var i = 0; i < mylinks.length; i++) {
Mylinks[i].addeventlistener (' Touchstart ', function () {this.classname = "hover";}, False);
Mylinks[i].addeventlistener (' Touchend ', function () {this.classname = "";}, False);
}


Then use CSS to add hover effects:

The code is as follows:
A:hover, A.hover {/* your hover effect */}


This way, you can design a link that feels more like a button. Also, this simulation can be used on any element.

Original address

Tips for mobile phone development: JavaScript and CSS function code sharing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.