Tips for mobile development: javascript and CSS code sharing

Source: Internet
Author: User

Tips for mobile development: javascript and CSS code sharing
This article mainly introduces essential tips for mobile phone Development: javascript and CSS code sharing. This article describes viewport (visible area) operations, Link Operations, javascript events, and so on, for more information, see

 

 

1. viewport:

That is, the visible area. For desktop browsers, we all know what the viewport is, that is, the area used to view the webpage after all the toolbar, Status Bar, and scroll bar are gone,
This is an effective region. Because the screen width of mobile devices is different from that of traditional web devices, we need to change the viewport;

In fact, we can operate on four attributes:

The Code is as follows:


Width-// The width of the viewport. The value ranges from 200 to 10,000. The default value is 980 pixels)
Height-// The height of the viewport (range from 223 to 10,000)

Initial-scale-// initial scaling ratio (range:> 0 to 10)

Minimum-scale-// minimum scale allowed by users
Maximum-scale-// maximum scale allowed by users

User-scalable-// can the user manually scale down (no, yes)


So how can we let Safari know about these settings? In fact, it is very simple, just a meta, like:

The Code is as follows:


<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"> // Encoding
<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 Offline Application Skill
<Meta name = "apple-mobile-web-app-status-bar-style" content = black "/> // hide the status bar
<Meta content = "black" name = "apple-mobile-web-app-status-bar-style"/> // specifies the style of the status bar at the top of safari on the iphone
<Meta content = "telephone = no" name = "format-detection"/> // tell the device to ignore recognizing numbers on the page as phone numbers
<Meta name = "Author" contect = "Mr. He"/>


After initial-scale = 1 is set, we can finally design the page at a ratio. Another important concept about viewport is that the iphone safari browser does not have a scroll bar at all, and does not simply "hide the scroll bar. The iphone's safari browser actually displays the webpage completely from the very beginning, and then uses viewport to view part of it. When you drag with your fingers, the page is not dragged, but the viewport. The browser behavior changes not only the scroll bar, but also the interaction events.

 

2. link:

The Code is as follows:


<Link rel = "apple-touch-startup-image" href?#startup.png "/> // set the start page image
<Link rel = "apple-touch-icon" href?”iphon_tetris_icon.png "/> // a nice icon is displayed when you set bookmarks.
<Link rel = "stylesheet" media = "all and (orientation: portrait)" href = "portrait.css"> // portrait Style
<Link rel = "stylesheet" media = "all and (orientation: landscape)" href = "landscape.css" // landscape Style

// The style used for Portrait Screen
<Style media = "all and (orientation: portrait)" type = "text/css">
# Landscape {display: none ;}
</Style>

// The style used for landscape Screen
<Style media = "all and (orientation: landscape)" type = "text/css">
# Portrait {display: none ;}
</Style>

 

3. Events:

The Code is as follows:


// Gesture event
Touchstart // triggered when the finger contacts the screen
Touchmove // triggered when the finger that has touched the screen starts to move
Touchend // triggered when the finger leaves the screen
Touchcancel

// Touch event
Gesturestart // triggered when two fingers touch the screen
Gesturechange // triggered when two fingers touch the screen and start to move
Gestureend

// Screen rotation event
Onorientationchange

// Detect when the touch screen finger changes direction
Orientationchange

// 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 (supported des scrolling)
PageY // Relative to the full page (supported des 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 listener to detect the screen rotation status at any time (left, right, or no rotation ). Example:

The Code is as follows:


// Determine whether 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-hand-90, screen-width:" + screen. width + "; screen-height:" + screen. height );
Break;
Case 90:
Alert ("right-hand 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 listening
AddEventListener ('load', function (){
OrientationChange ();
Window. onorientationchange = orientationChange;
});

 

5. Hide the address bar and prevent the scroll bar from appearing when handling events:

The Code is as follows:


// Hide the address bar and prevent the scroll bar from appearing when handling events
AddEventListener ('load', function (){
SetTimeout (function () {windows. scrollTo (0, 1) ;}, 100 );
});

 

6. Double-finger sliding event:

The Code is as follows:


// Double-finger slide event
AddEventListener ('load', function () {window. onmousewheel = twoFingerScroll ;},
False // compatible with various browsers, indicating that the event handler is called in the bubble phase (true capture phase)
);
Function twoFingerScroll (ev ){
Var delta = ev. wheelDelta/120; // judge the delta value (such as positive and negative), and then perform the corresponding operation
Return true;
};


7. Determine if the iPhone is used:

The Code is as follows:


// Determine whether the iPhone is used:
Function isAppleMobile (){
Return (navigator. platform. indexOf ('ipad ')! =-1 );
};

 

8. localStorage:

Example: (Note that the data name n must be enclosed in quotation marks)

The Code is as follows:


Var v = localStorage. getItem ('n ')? LocalStorage. getItem ('n'): ""; // if the data name is n, read it and assign it to the variable v.
LocalStorage. setItem ('n', v); // write data with the name n and value v
LocalStorage. removeItem ('n'); // delete data named n


9. Use special links:
If you disable automatic identification and want some phone numbers to be linked to the iPhone's dialing function, you can declare the phone link in this way,

The Code is as follows:


<A href = "tel: 12345654321"> call me </a>
<A href = "sms: 12345654321"> text message </a>


Or for cells:

The Code is as follows:


<Td onclick = "location. href = 'tel: 122 '">

 

10. Automatic uppercase and automatic correction
To disable these two functions, you can use the autocapitalize and autocorrect Options:

The Code is as follows:


<Input type = "text" autocapitalize = "off" autocorrect = "off"/>

 

11. WebKit CSS:
① The "Box Model" describes the content of the surrounding box blocks, including boundaries and fills.

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 rounded corner
-Webkit-box-sizing: sizing_model; border Constant Value: border-box/content-box
-Webkit-box-shadow: hoff voff blur color; // container shadow (parameters: horizontal X offset, vertical Y offset, Gaussian blur radius value, and 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) 25 25 25 25 round/stretch;
-Webkit-appearance: push-button; // built-in CSS representation. Currently, only push-button is supported.


② The "visual formatting model" describes the nature and determines the block elements of the position and size.

The Code is as follows:


Direction: rtl
Unicode-bidi: bidi-override; constant: bidi-override/embed/normal


③ "Visual effect" describes attributes and the content of the adjusted visual effect block, including overflow behavior, adjustment behavior, visibility, animation, transformation, and transition.

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 1 s linear; animated/linear/audio-in/audio-out/audio-in-out
-Webkit-backface-visibility: visibler; constant: 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 (,), to (rgba, 0, 0); // CSS mask/mask effect
-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)


④ The "generated content, automatic numbering, and listing" description attribute allows you to change an integral part of the content, create an automatic numbering chapter and title, and manipulate the style list content.

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 the properties of performance and appearance, and controls the behavior of printed web pages, such as paging characters.

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


⑥ "Color and background" describes the components of the block-level elements and text content of the color under the attribute control 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


7 "font" is a factor within the selection range of text fonts that describe the nature. The report also describes the attributes used to download the font definition.

The Code is as follows:


Unicode-range: U + 00-FF, U + 980-9FF;


Limit "text" describes the specific text style, spacing, and automatic scrolling of the attribute.

The Code is as follows:


Text-shadow: #00 FFFC 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 10 s; constant: direction (direction) increment (number of iterations) repetition (repetition) style (style) speed (speed );
-Webkit-marquee-direction: ahead/auto/backwards/down/forwards/left/reverse/right/up
-Webkit-marquee-incrementt: 1-n/infinite (infinite)
-Webkit-marquee-speed: fast/normal/slow
-Webkit-marquee-style: alternate/none/scroll/slide
-Webkit-text-fill-color: # ff6600; constant: 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 layout "table" describes the layout and specific content of the Design Performance 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


Refer "User Interface" description attribute, involving user interface elements in the browser, such as scrolling text area, scroll bar, and so on. The report also describes the properties outside the scope of the webpage content, such as the optical mark annotation style and display when you hold down the touch
Target, such as the 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 transition
This is the most innovative feature in Webkit: defining animations using transition functions.

The Code is as follows:


-Webkit-animation: title infinite injection-in-out 3 s;
Animation has the following attributes:
-Webkit-animation-name: // attribute name, which is the keyframes
-Webkit-animation-duration: 3 s // duration
-Webkit-animation-timing-function: // transition type: linear/linear (linear)/slow-in (slow to fast)/slow-out (fast to slow) /slow-in-out (slow to fast and then slow)/cubic-betiller
-Webkit-animation-delay: 10 ms // animation latency (0 by default)
-Webkit-animation-iteration-count: // number of cycles (1 by default), and infinite is unlimited
-Webkit-animation-direction: // animation Mode: normal (Forward playback by default); alternate (alternate direction, forward playback for the nth number, reverse playback for the odd number)


These can also be abbreviated. But what really impressed me is that keyframes can define an animation transformation process for calling, from 0% to 100% or from (0%) to (100% ). Simply put, as long as you have an idea, it is very easy to change the elements in this process.

The Code is as follows:


-Webkit-transform: type (scale/rotate/Tilt skew/shift 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) Skew angle. SkewX and skewY can be abbreviated as: skew (*,*)
Translate (*, *) coordinates. TranslateX and translateY can be abbreviated as: translate (*,*).


Example of simulating the pop-up message box (Alert:
① Define the transition (describe keyframes in the <style type = "text/css"> Section ):

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.5 s audio-in-out}


(It is easy to understand. scale down an element from 0.01 times-small but not 0 times, up to 1.05 times, down to 0.95 times, and then to 1 times, that is, the normal size. The entire transition event is 0.5 seconds, and the Animation Mode is slow-in-out, that is, slow to fast and then slow. By default, only one transition is performed. This is the animation effect of the prompt message displayed on the iPhone !)
② Define elements (in the <body> segment ):

The Code is as follows:


<Div id = "layerH" style = "-webkit-border-radius: 12px; border: 2px solid # FFF;-webkit-box-shadow: 0px 2px 4px #888; position: absolute; left: 24px; top: pixel PX; <br> width: 256px; height: 268px; padding-left: 8px; padding-right: 8px; color: # FFFFFF; text-shadow: 1px 1px 1px #000; text-align: center; background-color: RGBA (0.9, 48, 96 );
Background-image: url('BG-Msg.png '); background-repeat: no-repeat;
Z-index: 1; visibility: hidden; ">
<P> <span style = "font-size: 16pt; font-weight: bold"> usage instructions </span> </p>
<Hr noshade size = "1">
<Div id = "HelpText" style = "height: 120px"> description </div>
<Hr noshade size = "1">
<Form name = "formV" method = "POST">
<Input type = "button" value = "OK" 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 = 'den den '">
</Form>
</Div>


③ Start an animation (in a javascript-Defined Function)

The Code is as follows:


Function pHelp ()
{
LayerH. style. visibility = 'visable'
LayerH.style.css Text = "-webkit-animation-delay:" + Math. random () + "ms"
LayerH. className = 'szoom'
}


(This startup function is easy to understand. But why do we need to use the-webkit-animation-delay statement? This is because after an element transition is displayed, if its style does not change, the next transition animation cannot be displayed. We cleverly use the definition of the animation delay time to make it change, thus avoiding the above problems. The random number function Math. random () is used to generate a random number greater than 0 and less than 1. Of course, users will not notice the delay of a few milliseconds .)

 

Supplement:

1. Lock viewport

The Code is as follows:


Ontouchmove = "event. preventDefault ()" // lock the viewport. the user interface is not moved for any screen operations (except for the pop-up keyboard ).

 

2. The style can be used to set the appearance of the clicked element:

The Code is as follows:


-Webkit-tap-highlight-color: color


3. iPhone/iPod Detection
To develop a mobile website for a specific device, you must first perform device detection. The following describes how to use Javascript to detect the UA of the iPhone/iPod and then turn 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, users can still disable it. It will also cause the client to refresh and transmit additional data, so the following is 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. the font size is automatically adjusted when the screen is rotated.

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 CSS.
If you do not want to detect devices, you can use CSS media queries to define styles for iPhone/iPod.

Copy the Code as follows:


@ Media screen and (max-device-width: 480px ){}


6. Zoom out the image
Generally, a large image of a website is larger than 480 pixels in width. If you use the code above to limit scaling, the images displayed on the iPhone will obviously exceed the screen. Fortunately, the iPhone has enough functionality. We can use CSS to enable the iPhone to automatically scale down and display large images.

The Code is as follows:


@ Media screen and (max-device-width: 480px ){
Img {max-width: 100%; height: auto ;}
}


7. Simulation: hover pseudo class
Because the iPhone does not have a mouse pointer, there is no hover event. The CSS: hover pseudo class is useless. However, the iPhone has a Touch event. onTouchStart is similar to onMouseOver, and onTouchEnd is similar to onMouseOut. So we can use it to simulate hover. Use 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 increase the hover effect:

The Code is as follows:


A: hover, a. hover {/* your hover effect */}


In this way, you can design a link more like a button. In addition, this simulation can be used on any element.

 

Related Article

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.