Meta tags

1. Use meta tags to control viewPort
< meta name = “viewport” content = “width = device – width, initial – scale = 1.0, the maximum – scale = 1.0, user – scalable = no” / >
If you don’t, the default viewPort will be wider than the screen, which means a horizontal scroll bar will appear.
Width – Viewport Width height-viewport height
Initial-scale — The initial scale
Minimum-scale – The minimum scale to which the user is allowed to scale
Maximum-scale – The maximum scale to which the user is allowed to scale
User-scalable – Whether the user can scale manually
2. Remove the default Apple toolbar and menu bar
<meta name=”apple-mobile-web-app-capable” content=”yes”>
3. Color of the status bar (top of screen) in the Web App (Safari private meta tag in iPhone)
<meta name=”apple-mobile-web-app-status-bar-style” content=”black” />
The default is default (white), and can be black or black-always. 3.
A value of “Black-always” always occupies the px position and floats at the top of the page
4. Allow full screen browsing (Safari private meta tag on iPhone)
<meta content=”yes” name=”apple-mobile-web-app-capable”>
5. Banning the conversion of numbers to dial-up links
<meta name=”format-detection” content=”telephone=no”>
The default phone number on the iPhone is a hyperlink (blue font) and clicking the number will automatically dial

Second, use Ajax to get server-side data

Here’s a simple wrapper around jquery’s $.ajax() in real development:

mobile.myAjax=function(api,data,success,error){  $.ajax({        type:'POST',        url:preURL+api,        data:(typeof data==='object')? JSON.stringify(data):data, contentType:'application/json; charset=UTF-8',        success:success,        error:error || function(){           tips("System busy, data request failed!");         }     });}Copy the code

PreURL is the server address prefix and API is the interface address

An example of a call is as follows:

mobile.myAjax('cqeye/getProgramInfo',{cid:getId},function(data){if(data.code===0){ console.log(data); //data is the returned data}else{     tips('Failed to get data');  }}Copy the code

Click events delay 300ms (ios only)

Reason: After a user clicks on the screen, the browser can’t immediately determine whether the user wants to double click to zoom or click. So iOS Safari waits 300 milliseconds to see if the user has clicked on the screen again.
Solution:
FastClick is a lightweight library developed by FT Labs to solve the problem of 300-millisecond click delay in mobile browsers. In short, FastClick immediately fires a mock Click event via a DOM custom event when it detects a click event and blocks the actual click event that the browser fires 300 milliseconds later.
Using FastClick is as simple as calling FastClick.attach() on the body after the Window Load event.
window.addEventListener( “load”, function() {
FastClick.attach( document.body );
}, false );
Use lightweight mobile libraries such as Zepto.js that support TAP events to solve this problem, although they are slower to respond than FastClick
3. To solve the 300ms delay problem, you can also bind the onTouchStart event to speed up the response to the event
Response order of touch events
1, ontouchstart
2, ontouchmove
3, ontouchend
4, the onclick

Use the relative unit REM

Font-size :50px; line-height: 20px; font-size:50px; }, plus JS to enable the element’s width and height to change with the page’s width and height
The js code is as follows:

(function(doc, win) {
	var docEl = doc.documentElement,
	resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
	recalc = function() {
			var clientWidth = docEl.clientWidth < 720? docEl.clientWidth : 720
	  if(! clientWidth)return;
		docEl.style.fontSize = Math.floor(100 * (clientWidth / 640)) + 'px';
	  };
	 if(! doc.addEventListener)return;
	 win.addEventListener(resizeEvt, recalc, false);
	doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
Copy the code

When the page height is less than 720px, change the height and font size of the element by changing the font size of the root element.

5. Mobile phone screen rotation event onorientationChange

When the small video screen switches to full screen, add a monitor for screen direction change on the page, which will be triggered after invoking the native method, and we can perform corresponding operations according to the screen turning.
The js code is as follows:

window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", orientationChange, false);
function orientationChange(){
	var direction=window.orientation;
	if(direction = = = 0 | | direction = = = 180) {/ / vertical screen portrait}else if(direction = = = - 90 | | direction = = 90) {/ / landscape landscape}}Copy the code

Customize the return key

Sometimes simply calling the default return method of the browser cannot meet the needs of actual business. In this case, the local Storage of HTML5 needs to write the return key by itself: When the page jumps, the path of the current page is saved in the cache, and when the page returns, the returned path is obtained.
Page skipping:

function go(url){
	var backURI = location.href;
	var backUrlList = JSON.parse(localStorage['back_url_list'] | |'[]');
	var len=backUrlList.length;
	if(backUrlList[len-1]! =backURI){ backUrlList.push(backURI); // Save the current page address}localStorage['back_url_list'] = JSON. Stringify (backUrlList); location.href = url; }Copy the code

Returns:

function goBackParse (){/* backUrlList = json.parse (){/* backUrlList = json.parse ();localStorage['back_url_list'] | |'[]');
	var backURL = backUrlList.pop() || ('index.html');
	localStorage['back_url_list'] = JSON.stringify(backUrlList);
	var html=location.pathname;
	location.href = backURL;
}
Copy the code

7. Lazy loading of pictures

How it works: When visiting a page, replace the img element or other element’s background image path with a 1*1px image path (so you only need to request it once), and only set the image path to display when the image appears in the browser’s viewable area.
The js code is as follows:

; (function$(window).on($){$(window).on($){$(window).on('scroll resize load'.function(e){
var count = 0, screenHeight = $(window).height();
$('[data-lazy-src]').each(function(){ var pos = this.getBoundingClientRect(); // If the current image is above the field of view, keep looking downif(pos.bottom <= 0) return true; // If there are more than two images below the field of view, stop the search. This can only be judged from top to bottomif(pos.top >= screenHeight) return (count++)<2;
		var src = this.dataset.lazySrc;
		if(! src)return;
		if(this.nodeName === 'IMG') this.src = src;
		else this.style.backgroundImage = 'url(' + src + ') ';
		this.removeAttribute('data-lazy-src');
      });
   });
})(jQuery);Copy the code

The page application code is as follows:
<! Add a data-lazy-src attribute to div or img to create lazy images.

<div class="sample" style="backgrouond-image:url(images/spacer.gif)" data-lazy-src="images/02.jpg"></div><img class="sample" src="images/spacer.gif" data-lazy-src="images/02.jpg"/>Copy the code

8. Hide text beyond a fixed number of lines

1. Hide text beyond one line
.text{overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .24rem; }
2, text beyond 2 lines hidden
.text-line2{display: -webkit-box! important; overflow: hidden; text-overflow: ellipsis; word-break: break-all; -webkit-box-orient: vertical; -webkit-line-clamp:2; }

Gets how far the gesture slides within an element

The js code is as follows:

$('#play-content').on('touchstart'.function(e){
     startX = e.originalEvent.touches[0].pageX;
     startY = e.originalEvent.touches[0].pageY;
 }).on('touchmove'.function[c].hello.view [0].view; var endY = e.originalEvent.touches[0].pageY; var moveX=parseInt(endX - startX); var moveY=parseInt(endY - startY); var disX=moveX<0? moveX*(-1):moveX; Var disY=moveY<0? moveY*(-1):moveY; });Copy the code

Ten, page knowledge

1. In the ios browser, hold down the A tag on the HTML page to display the browser’s built-in menu. You can also access the corresponding link page by clicking the option in the menu.
/* Disables ios from triggering the system menu for a long time, and prevents ios&Android from downloading images for a long time */
*:not(input,textarea) { -webkit-touch-callout: none; touch-callout: none; -webkit-user-select: none; user-select: none; }
2. If you want to customize the width/height ratio of an image without distorting the image, you can center the image with the background of a div
Div styles are set as follows:
.back-img{background-position: 50% 50%; background-size: cover; }
3, when the page has an input box, click the input box to enter the content of the mobile phone will pop up a soft keyboard, the browser may move the whole page up, you can set the entire HTML {position:fixed; width:100%; } keep the entire page fixed;
If the keyboard completely blocks the input field, you can set the page header{position:fixed; width:100%; } fixed the page header so that the browser automatically places the content below the page header to display the input field.
$(‘#id’).focus(); $(‘#id’)[0].focus();
5. In jquery Ajax, $(this) becomes jquery’s XHR object, so get this and assign it to a local variable before ajax
Dom.width (10rem) = 10rem+padding(px)+border(px);
If you set dom.css (width,10rem), the total width is 10rem
7, object.keys (obj). Length Calculates the length of Object obj
8. The value of -webkit-user-select
None: Text cannot be selected
Text: You can select a text
All: Can be selected when all content is considered as a whole. If you double-click or contextually click on a child element, the selected portion will be the highest ancestor element traced back to that child element.
Element: You can select text, but the selection is limited by element boundaries
$(‘#id’).css(‘background-image’) $(‘#id’).css(‘background-image’)
Url (“aa.jpg”) or URL (aa.jpg). If we want to use the path of this image, we should remove the quotation marks first, otherwise it will be wrong;
$(‘#id’).css(‘background-image’).replace(/”/g,”).slice(4,-1); Get aa. JPG