Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

preface

We have collected 40 front-end tips for solving mobile Web page problems, hoping to help you reduce your development time and increase your time. I will post more tips in the future

1, Android browser when looking at the background image, some devices will be blurred.

With equal proportions, the image is clear on a PC, but blurry on a mobile phone. Why?

After research, devicePixelRatio is the problem, because the resolution of mobile phone is too small, if the webpage is displayed according to the resolution, the words will be very small, so Apple originally put iPhone 4 960640 resolution, only 480320 in the webpage, so devicePixelRatio = 2. Now Android is messy, there are 1.5, 2 and 3.

To make the image look better on the phone, you must use a 2x background image instead of the IMG tag (usually 2x). Background-size :contain; background-size:contain; “, so that the display of the picture is clearer.

The code could look like this:

background:url(.. /images/icon/all.png) no-repeat center center; -webkit-background-size:50px 50px; background-size: 50px 50px; display:inline-block; width:100%; height:50px;  
Copy the code

Background-size :contain; All right, everybody try it!

2. Image loading

If you encounter the problem of slow image loading, in this case, mobile development generally use canvas method loading:

Specific see the canvas API: javascript.ruanyifeng.com/htmlapi/can…

Here is an example of a canvas:

<li><canvas></canvas></li> 
Copy the code

Js dynamic loading images and Li a total of 17 examples of images!

var total=17; 
var zWin=$(window); 
var render=function(){ 
  var padding=2; 
  var winWidth=zWin.width(); 
  var picWidth=Math.floor((winWidth-padding*3) /4); 
  var tmpl =' '; 
  for (var i=1; i<=totla; i++){var p=padding; 
  var imgSrc='img/'+i+'.jpg'; 
  if(i%4= =1){ 
   p=0; 
  } 
  tmpl +='<li style="width:'+picWidth+'px; height:'+picWidth+'px; padding-left:'+p+'px; padding-top:'+padding+'px;" >+i+'"></canvas></li>'; 
  var imageObj = new Image(); 
  imageObj.index = i; 
  imageObj.onload = function(){ 
    var cvs =$('#cvs_'+this.index)[0].getContext('2d'); 
    cvs.width = this.width; 
    cvs.height=this.height; 
    cvs.drawImage(this.0.0); 
  } 
  imageObj.src=imgSrc; 
  } 
 
} 
render(); 
Copy the code

3. If the mobile website is not compatible with Internet Explorer, we usually use ZeptoJS. Zeptojs has a built-in Touch Events methodzeptojs.com/#Touch events

Have a look at the new version of zeptio API, already support IE10 or above, zeptoJS can choose to use!

4, prevent mobile web pages from zooming in and out, this is the most basic, most mobile web developers should know, is to set the meta viewport

In addition, some mobile sites we see the following statement:

The copy code is as follows:

<! DOCTYPEhtml PUBLIC "- / / WAPFORUM/Mobile/DTD XHTML 1.0 / / EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
Copy the code

The way to set the DTD is to write XHTML, if our page uses HTML5, can not set the DTD, directly declare.

Use viewPort to disable page zooming. User-scalable is often set to 0 to shut down user scaling of the page view.

<meta name="viewport" content="user-scalable=0" />
Copy the code

But for better compatibility, we’ll use the full viewPort setup.

The copy code is as follows:

<meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = 0" />
Copy the code

And, of course, user-scalable=0, or even user-scalable=no.

5, apple — mobile web app — capable

Apple-mobile-web-app-capable Specifies whether web applications run in full-screen mode.

Grammar:

<meta name="apple-mobile-web-app-capable" content="yes">
Copy the code

Description:

If content is set to Yes, the Web application will run in full-screen mode; otherwise, it will not. The default value of Content is no, which indicates normal display. You can use the read-only property window. The navigator. Standalone to determine whether the page displayed in full screen mode.

6, the format – detection

Format-detection Enables or disables automatic identification of phone numbers on a page.

Grammar:

<meta name="format-detection" content="telephone=no">
Copy the code

Description:

By default, the device automatically recognizes any string that could be a phone number. Setting telephone=no disables this function.

7. Html5 calls android or ios dial functions

Html5 provides a tag that automatically calls the dial, just add tel: to the href of the A tag.

As follows:

<a href="Tel: 4008106999103">The 400-810-6999 to 1034</a>
Copy the code

Dial the phone directly below

 <a href="tel:15677776767">Click to call 15677776767</a>
Copy the code

8. Html5GPS positioning function

See: www.jb51.net/post/html5_…

9. Slow and slow when pulling the scroll bar up and down

body {
  -webkit-overflow-scrolling: touch;
  overflow-scrolling: touch;
}
Copy the code

Android3+ and iOS5+ support overflow-scrolling for CSS3

10. Forbid copying and selecting text

Element {
  -webkit-user-select: none;
  -moz-user-select: none;
  -khtml-user-select: none;
   user-select: none;
}
Copy the code

Solution for selectable page text on mobile devices (depending on product needs)

11, long time to hold the page flash back

element {
  -webkit-touch-callout: none;
}
Copy the code

12, iPhone and iPad input box default inner shadow

Element{
  -webkit-appearance: none; 
}
Copy the code

13. Translucent gray masks appear on touch elements on ios and Android

Element {
  -webkit-tap-highlight-color:rgba(255.255.255.0)}Copy the code

Set alpha to 0 to remove the translucent grey mask. Note: Transparent does not work on Android.

The following article has detailed introduction, address: www.jb51.net/post/phone_…

14, active compatible processing is pseudo class :active invalid

  1. Method 1: Add onTouchStart to body
<body ontouchstart="">
Copy the code
  1. Method 2: JS binds the TouchStart or TouchEnd event to the document
<style>
a {
 color: # 000;
}
a:active {
 color: #fff;
}
</style>
<a herf=foo >bar</a>
<script>
 document.addEventListener('touchstart'.function(){},false);
</script>
Copy the code

15, animation definition 3D enable hardware acceleration

Element {
  -webkit-transform:translate3d(0.0.0)
  transform: translate3d(0.0.0);
}
Copy the code

Note: 3D deformation consumes more memory and power

16. 1px border for Retina Display

Element{
  border-width: thin;
}
Copy the code

17. Webkit Mask compatibility processing

Some low-end phones do not support CSS3 masks and can be demoted selectively.

For example, we can use js judgment to reference different classes:

if( 'WebkitMask' in document.documentElement.style){
  alert('support mask');
} else {
  alert('Mask not supported');
}
Copy the code

18. Font size adjustment issues when rotating the screen

html.body.form.fieldset.p.div.h1.h2.h3.h4.h5.h6 {
  -webkit-text-size-adjust:100%;
}
Copy the code

19. Transition Screen

/ Sets the embedded element in3How is D space presented: reserved3D /
 
-webkit-transform-style: preserve-3d; / Sets whether the back of the converted element is visible to the user: hide / -webkit-backface-visibility:hidden;
Copy the code

20. Rounded corners bug

The rounded corners of some Android phones fail

background-clip: padding-box;
Copy the code

21. Background color of top status bar

<meta name="apple-mobile-web-app-status-bar-style" content="black" />
Copy the code

Description:

This meta tag won’t work unless you first specify full-screen mode using Apple-mobile-web-app-capable.

If content is set to Default, the status bar displays normally. If set to blank, the status bar will have a black background. If set to blank- always, the status bar appears as black and translucent. If it is set to Default or Blank, the page is displayed at the bottom of the status bar, that is, the status bar occupies the top part and the page occupies the bottom part. The two do not block each other or are blocked. If set to blank- up, the page always fills the screen, with the top obscured by the status bar (covering 20px, as opposed to 40px on the iphone4 and itouch4 Retina screens). The default value is default.

22. Set the cache

<meta http-equiv="Cache-Control" content="no-cache" />
Copy the code

Mobile pages are typically cached after the first load, and then each refresh uses the cache instead of rerunning requests to the server. If you do not want to use cache, you can set no-cache.

23. Desktop ICONS

<link rel="apple-touch-icon" href="touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png" />
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png" />
Copy the code

In iOS, desktop ICONS are defined for different devices. If not, use the current screen shot as the icon.

The above writing method may feel that there will be a default luster, the following setting method can remove the luster effect, restore the design effect!

<link rel="apple-touch-icon-precomposed" href="touch-icon-iphone.png" />
Copy the code

The image size can be 5757 (px) or 114114 (px) for Retina, and 72 by 72 (px) for iPad.

24. Splash screen

<link rel="apple-touch-startup-image" href="start.png"/>
Copy the code

In iOS, a screen is displayed when a page is loaded, avoiding a blank screen.

Different sizes can be specified by madia:

<! --iPhone-->
<link href="apple-touch-startup-image-320x460.png" media="(device-width: 320px)" rel="apple-touch-startup-image" />
 
<! -- iPhone Retina -->
<link href="apple-touch-startup-image-640x920.png" media="(device-width: 320px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />
 
<! -- iPhone 5 -->
<link rel="apple-touch-startup-image" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)" href="apple-touch-startup-image-640x1096.png">
 
<! -- iPad portrait -->
<link href="apple-touch-startup-image-768x1004.png" media="(device-width: 768px) and (orientation: portrait)" rel="apple-touch-startup-image" />
 
<! -- iPad landscape -->
<link href="apple-touch-startup-image-748x1024.png" media="(device-width: 768px) and (orientation: landscape)" rel="apple-touch-startup-image" />
 
<! -- iPad Retina portrait -->
<link href="apple-touch-startup-image-1536x2008.png" media="(device-width: 1536px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />
 
<! -- iPad Retina landscape -->
<link href="apple-touch-startup-image-1496x2048.png"media="(device-width: 1536px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2)"rel="apple-touch-startup-image" />
Copy the code

25, browser private and other meta

The following properties are not used in the project, you can write a demo to test the following properties!

QQ browser private

Full screen mode

<meta name="x5-fullscreen" content="true">

Mandatory vertical screen

<meta name="x5-orientation" content="portrait">

Mandatory landscape

<meta name="x5-orientation" content="landscape">

Application mode

<meta name="x5-page-mode" content="app">

UC Browser Private

Full screen mode

<meta name="full-screen" content="yes">

Mandatory vertical screen

<meta name="screen-orientation" content="portrait">

Mandatory landscape

<meta name="screen-orientation" content="landscape">

Application mode

<meta name="browsermode" content="application">

other

Optimized for handheld devices, mainly for older browsers that don’t recognize viewports, such as blackberry

<meta name="HandheldFriendly" content="true">

Microsoft’s old browser

<meta name="MobileOptimized" content="320">

Windows Phone click without highlights

<meta name="msapplication-tap-highlight" content="no">

IOS input events keyup, keyDown, keypress are not well supported

The problem is that when you use input Search to do fuzzy search, you will enter keywords in the keyboard, and then you will return data through Ajax background query, and then you will red the returned data with keywords. Use input to listen for keyup events on the keyboard, it is possible in Android mobile phone browser, but in ios mobile phone browser red slowly, with input method after input, not immediately corresponding to the keyup event, only after the deletion can be corresponding!

Solutions:

Instead of keyUp, you can use html5 onInput events

<input type="text" id="testInput">
<script type="text/javascript">
  document.getElementById('testInput').addEventListener('input'.function(e){
    var value = e.target.value;
  });
</script>
Copy the code

Then something like keyUp is achieved!

H5 website input set to type=number

H5 page input type set to number usually causes three problems. One problem is that the maxLength attribute does not work well. When the form is submitted, it is rounded by default. Third, some Android phones have style problems.

  1. Problem solved, I am currently using JS. The following
<input type="number" oninput="checkTextLength(this ,10)"> 
<script>
function checkTextLength(obj, length) {  
      if(obj.value.length > length)  {     
        obj.value = obj.value.substr(0, length); }}</script>
Copy the code
  1. The default value of step is 1. To set the step attribute, if 2 decimal places are reserved, write as follows:

< input type = "number" step = "0.01" / >

As for step, I will make a brief introduction here. In the input type=number, an up and down arrow is automatically generated. Clicking the up arrow adds a step by default, and clicking the down arrow reduces a step by default. The default step in number is 1. Step =0.01, you can enter 2 decimal places, and click the up and down arrows to increase and decrease 0.01, respectively.

If step and min are used together, the value must be between min and Max.

Look at the following example:

<input type="number" step="3.1" min="1" />

What numbers can be entered into the input box?

First, the minimum value is 1, so you can enter 1.0, the second value is (1+3.1) that is 4.1, and so on, each click of the up and down arrow will increase or decrease 3.1, input other numbers are invalid. So that’s a brief introduction to step.

  1. Problem three: Get rid of the default input style
input[type=number] {
  -moz-appearance:textfield;
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
Copy the code

28. Ios Settings for the Input button style are overridden by the default style

Solutions are as follows:

input.textarea {
  border: 0; 
  -webkit-appearance: none; 
}
Copy the code

Set the default style to None

29, IOS keyboard letter input, the default initial letter uppercase

Solution, set the following properties

<input type="text" autocapitalize="off" />

30, select the right alignment from the select drop-down list

The Settings are as follows:

select option {
 direction: rtl;
}
Copy the code

31. Skew is deformed by Transform and rotate causes a sawtooth phenomenon

It can be set as follows:

-webkit-transform: rotate(-4deg) skew(10deg) translateZ(0);
 transform: rotate(-4deg) skew(10deg) translateZ(0);
 outline: 1px solid rgba(255.255.255.0)
Copy the code

32, mobile terminal click 300ms delay

300ms is acceptable, but we have to solve the problem caused by 300ms. The user experience is not very good at 300ms. To solve this problem, we usually use tap events instead of click events on the mobile side.

Recommend two js, fastclick and tap.js

About 300 ms delay, specific see: THX. Making. IO/mobile / 300 m…

Mobile endpoint penetration problem

Examples are as follows:

<div id="haorooms">Nod event test</div>
 
<a href="www.jb51.net">www.jb51.net</a>
Copy the code

Div is an absolutely positioned mask with a Z-index higher than a. The a tag is a link in the page, and we bind the div to the tap event:

$('#haorooms').on('tap'.function(){$('#haorooms').hide();
});
Copy the code

When we click on the mask, the div disappears normally, but when we click on the mask on the A tag, we find that the A link is triggered, which is called the tap through event.

The reason:

Touchstart precedes TouchEnd before Click. Click is triggered by a delay of about 300ms, which means that after the tap is triggered, the mask is hidden, and then the click is not triggered. 300ms later, due to the mask is hidden, our click is triggered on the following link A. Solution:

  1. Use touch events instead of click events whenever possible. For example, use the Touchend event (recommended).
  2. Use fastclick github.com/ftlabs/fast…
  3. PreventDefault prevents click on the A TAB
  4. Delay events for a certain amount of time (300ms+) (not recommended)
  5. This usually works, but if not, use the Click event.

Here’s the touchend event, as follows:

$("#haorooms").on("touchend".function (event) {
   event.preventDefault();
});
Copy the code

34. Eliminate the cross in IE10

input:-ms-clear{display:none; }Copy the code

35. Optimization of fonts on iOS and OS X (inconsistent bold fonts on vertical and horizontal screens)

Setting text-size-adjust to None will fix the problem on iOS when the browser resets the font size when it is landscape, but the desktop Version of Safari does not allow font scaling, so the best solution is to set text-size-adjust to 100%.

-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
text-size-adjust: 100%;
Copy the code

36. In iOS, when Chinese input method is used to input English, there may be a space of 1/6 between letters

You can get rid of it by re

this.value = this.value.replace(/\u2006/g.' ');
Copy the code

37. Mobile HTML5 Audio autoplay failure

This is not a BUG, because the automatic playing of audio or video in web pages will bring some confusion or unnecessary traffic consumption to users, so apple system and Android system usually prohibit automatic playing and JS trigger playing, which can only be triggered by users.

Solution idea: first touch by user touchStart, trigger play and pause (audio starts to load, then use JS to operate again no problem).

Solution code:

document.addEventListener('touchstart'.function () {
  document.getElementsByTagName('audio') [0].play();
  document.getElementsByTagName('audio') [0].pause();
});
Copy the code

38, mobile HTML5 input date does not support placeholder problems

I feel that there is no good solution to this problem. How to use the following method

The copy code is as follows:

<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')"  id="date">
Copy the code

Some browsers may need to click twice!

39. Some models have input whose type is Search, and its own modification method of close button style

Some models of the search Input control come with a close button (a pseudo-element), but in order to be compatible with all browsers, we will implement one ourselves. In this case, the method to remove the native close button is as follows

#Search::-webkit-search-cancel-button{
  display: none;  
}
Copy the code

If you want to use the native close button and make it fit your design style, you can modify the style of this pseudo-element.

Invoke the option expansion of select

Zepto way:

$(sltElement).trrgger("mousedown");

Native JS mode:

function showDropdown(sltElement) {
  var event;
  event = document.createEvent('MouseEvents');
  event.initMouseEvent('mousedown'.true.true.window);
  sltElement.dispatchEvent(event);
};
Copy the code