Common problems and precautions of H5 project

Keywords: Attribute Android iOS Mobile

Common problems and precautions of H5 project

Meta Basic Knowledge:

  • H5 page window automatically adjusts to device width and prohibits users from scaling pages
//I. HTML Page Structure
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
// Width sets the viewport width to a positive integer or string'device-width'
// Heights set viewport height, generally set the width, will automatically resolve the height, you can not set
// The default scaling ratio for initial-scale is a number with decimal
// Mini-scale allows users to zoom in to a minimum of one digit, with decimal numbers
// Maxim-scale allows users to zoom in to a maximum of one digit, with decimal numbers
// Is user-scale allowed to zoom manually

//II. JS Dynamic Judgment
var phoneWidth =  parseInt(window.screen.width);
var phoneScale = phoneWidth/640;
var ua = navigator.userAgent;
if (/Android (\d+\.\d+)/.test(ua)){
    var version = parseFloat(RegExp.$1);
    if(version>2.3){
        document.write('<meta name="viewport" content="width=640, minimum-scale = '+phoneScale+', maximum-scale = '+phoneScale+', target-densitydpi=device-dpi">');
    }else{
        document.write('<meta name="viewport" content="width=640, target-densitydpi=device-dpi">');
    }
} else {
    document.write('<meta name="viewport" content="width=640, user-scalable=no, target-densitydpi=device-dpi">');
}
  • H5 blank page basic meta tag
<! - Set zoom - >.
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimal-ui" />
<! - Hidden address bar, only for Safari of IOS. (Note: After IOS 7.0, Safari has no effect)--> ____________
<meta name="apple-mobile-web-app-capable" content="yes" />
<! -- Safari top status bar style for IOS only (defau lt/black/black-translucent is optional) --> ____________
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<! - Disable number recognition as phone number in IOS / Ignore email address recognition in Android platform - >
<meta name="format-detection"content="telephone=no, email=no" />
  • PC-side basic meta tag
<! - Page keywords - >
<meta name="keywords" content="your tags" />
<! - Page Description - >
<meta name="description" content="150 words" />
<! - Search engine indexing: robotters are a set of comma (,) partitioned values, usually with the following values: none, noindex, nofollow, all, index and follow. Ensure that nofollow and Noindex attribute values are used correctly. >
<meta name="robots" content="index,follow" />
<!--
    all: The file will be retrieved and the links on the page can be queried.
    none: Documents will not be retrieved, and links on pages can not be queried;
    index: The file will be retrieved;
    follow: Links on the page can be queried.
    noindex: Files will not be retrieved;
    nofollow: Links on pages cannot be queried.
 -->

 <! - Page redirection and refresh: The number in content represents time (seconds), and how much time to refresh after that. If you add url, it will be redirected to the designated page (search engines can automatically detect, and it is easy for the engine to be misled and punished). >
 <meta http-equiv="refresh" content="0;url=" />
  • Page caching settings
<!-- Clear cache -->
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
  • Other meta tags
<! - Enable 360 browser's extreme speed mode (webkit) -->
<meta name="renderer" content="webkit">
<! - Avoid IE using compatibility mode - >
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<! - Optimizing for handheld devices, mainly for older browsers that don't recognize viewport, such as BlackBerry - >
<meta name="HandheldFriendly" content="true">
<! - Microsoft's old browser - >
<meta name="MobileOptimized" content="320">
<! - UC Forced Vertical Screen - >
<meta name="screen-orientation" content="portrait">
<! - QQ Forced Vertical Screen - >
<meta name="x5-orientation" content="portrait">
<! - UC Forced Full Screen - >
<meta name="full-screen" content="yes">
<! - QQ Forced Full Screen - >
<meta name="x5-fullscreen" content="true">
<! - UC application mode - > UC application mode, UC application mode, UC application mode, UC application mode, UC application mode, UC application mode, UC application mode, UC application mode, UC application mode, UC application mode
<meta name="browsermode" content="application">
<! - QQ application mode - > QQ application mode, QQ application mode, QQ application mode, QQ application mode, QQ application mode, QQ application mode, QQ application mode, QQ application mode, QQ application mode, QQ application mode,
<meta name="x5-page-mode" content="app">
<! - Windows Phone click No highlight - >
<meta name="msapplication-tap-highlight" content="no">

<meta name="author" content="author name"/> <!--Define the author of a web page-->
<meta name="google" content="index,follow" />
<meta name="googlebot" content="index,follow" />
<meta name="verify" content="index,follow" />

Common problem:

  • How to define font-family on mobile end
@ --------------------------------------English Name of Chinese Font
@ Song style      SimSun
@ Blackbody      SimHei
@ WeChat black   Microsoft Yahei
@ Microsoft JhengHei Microsoft JhengHei
@ NSimSun    NSimSun
@ Neo thinning body  MingLiU
@ Thin and bright body    MingLiU
@ DFKai-SB    DFKai-SB
@ Imitation song     FangSong
@ Regular script     KaiTi
@ Imitation song_GB2312  FangSong_GB2312
@ Regular script_GB2312  KaiTi_GB2312  
@
@ Note: Most Chinese fonts are in Song style, Yahei style and English style. Helvetica

body { font-family: Microsoft Yahei,SimSun,Helvetica; } 
  • How to Realize Calling, Sending Short Messages and Writing Emails
// I. Telephone calls
<a href="tel:0755-10086">Phoning:0755-10086</a>

//  2. Sending SMS, winphone system is invalid
<a href="sms:10086">Send text messages to: 10086</a>

// 3. Writing E-mail
//Note: When adding these functions, the first function begins with "?" and the last one begins with "&".
//1. Ordinary mail
<a href="mailto:863139978@qq.com">Click on me to send an email</a>
//2. Add? cc = at the beginning after the receiving address, and add a copy address (Android has compatibility problems)
<a href="mailto:863139978@qq.com?cc=zhangqian0406@yeah.net">Click on me to send an email</a>
//3. Following the copy address, write & bcc= and add the encrypted copy address (Android has compatibility problems)
<a href="mailto:863139978@qq.com?cc=zhangqian0406@yeah.net&bcc=384900096@qq.com">Click on me to send an email</a>
//4. Contains multiple recipients, transcripts, and Bcc, separated by semicolons (;)
<a href="mailto:863139978@qq.com;384900096@qq.com">Click on me to send an email</a>
//5. Include themes, use subject?=
<a href="mailto:863139978@qq.com?subject=Mail theme">Click on me to send an email</a>
//6. Include content, use body=; if content contains text, use% 0A to wrap text lines 
<a href="mailto:863139978@qq.com?body=Mail Subject Content%0A Tencent integrity%0A Looking forward to your arrival">Click on me to send an email</a>
//7. Content contains links, and text with http(s): // etc. is automatically converted into links
<a href="mailto:863139978@qq.com?body=http://www.baidu.com">Click on me to send an email</a>
//8. Content includes pictures (PC does not support)
<a href="mailto:863139978@qq.com?body=<img src='images/1.jpg' />">Click on me to send an email</a>
//9. Complete examples
<a href="mailto:863139978@qq.com;384900096@qq.com?cc=zhangqian0406@yeah.net&bcc=993233461@qq.com&subject=[Mail theme]&body=Tencent invites you to participate%0A%0Ahttp://www.baidu.com%0A%0A<img src='images/1.jpg' />">Click on me to send an email</a>
  • Mobile touch events (distinguishing webkit from winphone)
/* touch events triggered when the user's finger is placed on the mobile device and slides on the screen */
// The following support webkit
touchstart——It happens when the finger touches the screen. No matter how many fingers there are at present
touchmove——Triggered continuously when the finger slides on the screen. Usually when we slide the page again, we call it event Of preventDefault()Prevent defaults: Prevent page scrolling
touchend——Triggered when the finger leaves the screen
touchcancel——The system triggers when it stops tracking the touch. For example, a sudden page in the process of touching alert()A prompt box, which triggers the event, is less frequently used

//TouchEvent explains:
touches: Information on all fingers on the screen
targetTouches: Finger information in target area
changedTouches: Finger information that triggered the last event
touchend At that time, touches and targetTouches The information will be deleted. changedTouches The last information saved is best used to calculate finger information

//Parameter information (changed Touches [0])
clientX,clientY Coordinates in the display area
target: Current element

//Sequence of event response
ontouchstart  > ontouchmove  > ontouchend > onclick

// The following support winphone 8
MSPointerDown——It happens when the finger touches the screen. No matter how many fingers there are at present
MSPointerMove——Triggered continuously when the finger slides on the screen. Usually when we slide the page again, we call it css Of html{-ms-touch-action: none;}Prevent defaults: Prevent page scrolling
MSPointerUp——Triggered when the finger leaves the screen
  • Delayed response of 200-300ms generated by mobile click screen
Note: web pages on mobile devices have 300 ms delay. Playing can cause button click delay or even click failure.

The following are historical reasons, from the sharing of a colleague in a company:
In 2007, Apple released safari, the first IOS system on the iphone. In order to display the large screen pages on the PC better on the mobile phone, safari used a double tap to zoom scheme. For example, when you open a web page on the PC with a browser on the mobile phone, you may see that the content of the page can fill the whole screen, but the font and picture are very small. If you can't see clearly, you can quickly double-click on a part of the screen, and you can see the magnified content of that part, and then double-click again to return to the original state.

Double-click zooming refers to two quick clicks on the screen with your finger. The Safari browser with iOS will zoom the page to its original scale.

The reason lies in how the browser needs to determine the quick click. When the user clicks on an element on the screen, such as jump link < a href=""> </a>, the browser will capture the click first, but the browser can not decide whether the user clicks on the link or double-clicks on the partition to zoom in. Therefore, after the first click, the browser will first Hol. If the user does not click the next time in the T-Time interval, the browser will do the click-jump link processing. If the user clicks the second time in the T-Time interval, the browser will prohibit the jump, and then the browser will scale the pages in this part of the area. So what is the time interval t? Under IOS safari, it's about 300 milliseconds. That's where the delay comes from. As a result, the user clicks the page purely, and the page needs a period of time to respond, giving the user a sense of slow experience. For web developers, the page js captures the click event callback function processing, which takes 300 ms to take effect, which indirectly leads to the processing of other business logic.

// Solutions:
Fasstclick can solve 300 ms delay of clicking events on mobile phones
 zepto touch module, tap event is also to solve the problem of delay in click
  • Principle and design scheme of Rentina display screen
Description: The retina screen is a liquid crystal screen with super high pixel density. The pixels displayed on the same size screen change from one to more. For example, on the same screen with the same tape, in the retina screen of Apple device, one pixel becomes four.
The bitmap in the HD display is enlarged and blurred, so the visual manuscript on the mobile side is usually designed to be twice as large as that on the traditional PC.
The front-end solution, then, is to ensure that the length and width of the cut-out pictures are even, and use backgroud-size to reduce the pictures to 1/2 of the original.

// For example, if the width and height of the picture are: 200px*200px, then the writing is as follows
.css{width:100px;height:100px;background-size:100px 100px;}
// The other elements are taken as 1/2 of the original value, such as the font of visual manuscript 40px, which is written in 20px style.
.css{font-size:20px}

// image-set Design Rentina Background Map
 Image-set, the WebKit private property, is also an attribute of CSS4, which is created to solve the problem of images on Rentina screen.
.css {
    background: url(images/bg.jpg) no-repeat center;
    background: -webkit-image-set(
    url(images/bg.jpg) 1x, / / / support image-set ordinary screen
    URL (images/bg-2x.jpg)2x); //entinan supporting image-set
}
  • Click on the element to create the background or border. How to remove it?
//ios users click on a link and a translucent grey mask appears. If you want to disable it, you can set the alpha value of - webkit-tap-highlight-color to 0 to remove the gray translucent mask.
//android users click on a link, and a border or translucent gray mask will appear. Different manufacturers define different amount of effect. The alpha value of webkit-tap-highlight-color can be set to 0 to remove the effect of some machines.
//In winphone system, the gray translucent background generated by clicking on the label can be removed by setting < meta name= "msapplication-tap-highlight" content= "no";
//Special note: Some models can not be removed, such as millet 2. There is another way for button classes to use div tags instead of a or input tags.
a,button,input,textarea { 
    -webkit-tap-highlight-color: rgba(0,0,0,0); 
    -webkit-user-modify:read-write-plaintext-only; //- One side effect of webkit-user-modify is that the input method can no longer input multiple characters.
}   
// It's fine too 
* { -webkit-tap-highlight-color: rgba(0,0,0,0); }
//Under winphone
<meta name="msapplication-tap-highlight" content="no">
  • Beautifying Form Elements
//1. Use appearances to change the default appearance of webkit browsers
input,select { -webkit-appearance:none; appearance: none; }

//2. Using pseudo-elements to change the default appearance of form elements under winphone
//1. Disable the select Default arrow: -ms-expand modifies the form control drop-down arrow, sets hiding and modifies it with background images
select::-ms-expand { display:none; }

//2. Disable the default styles of radio and checkbox: -ms-check modifies the default icons of form checkboxes or radio boxes, sets hiding and modifies them with background images
input[type=radio]::-ms-check,
input[type=checkbox]::-ms-check { display:none; }

//3. Disable the default clearance button for the form input box on the pc side: -ms-clear modifies the clearance button, sets hiding and uses background images to modify it.
input[type=text]::-ms-clear,
input[type=tel]::-ms-clear,
input[type=number]::-ms-clear { display:none; }
  • font-size for mobile font unit to choose px or rem
// rem is recommended for adapting to multiple mobile devices. The following are the reference values:
html { font-size: 62.5%; }   //10*16 = 62.5%
//Setting up the 12px font here pay attention to adding the corresponding PX value before rem, solve the compatibility problem of browsers that do not support rem, and achieve elegant degradation.
body { font-size:12px; font-size:1.2rem; }     
  • Super Practical CSS Style
//Remove the scroll bar of webkit - display: none;
//Other parameters
::-webkit-scrollba //Scrollbar integral part
::-webkit-scrollbar-thumb   //Small squares in the scroll bar
::-webkit-scrollbar-track   //Rolling bar track
::-webkit-scrollbar-button  //Buttons at both ends of the scrollbar track
::-webkit-scrollbar-track-piece  //The middle part of the scroll bar, the built-in track
::-webkit-scrollbar-corner       //Edge corner, where two scrollbars intersect
::-webkit-resizer            //A small control at the intersection of two scrollbars for resizing elements by dragging

// Long-click links and picture pop-up menus are prohibited
a,img { -webkit-touch-callout: none }    

// Prohibit ios and android users from selecting Chinese characters
html,body {-webkit-user-select:none; user-select: none; }

// Change the color value of the input box placeholder
::-webkit-input-placeholder { /* WebKit browsers */
color: #999; }
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: #999; }
::-moz-placeholder { /* Mozilla Firefox 19+ */
color: #999; }
:-ms-input-placeholder { /* Internet Explorer 10+ */
color: #999; }
input:focus::-webkit-input-placeholder{ color:#999; }

// android Remove Voice Input Button
input::-webkit-input-speech-button {display: none}

// Prevent default touch events on windows Phone
/*Description: The default touch event event event using e.preventDefault under winphone is invalid and can be disabled by style, such as:*/
html { -ms-touch-action:none; } //Disable winphone default touch events
  • Cancel the default capitalization of the English initials when input ting under ios
<input autocapitalize="off" autocorrect="off" />
  • Mobile Photo and Upload Pictures
//IOS has the functions of taking pictures, videos and choosing local pictures. Some Android s only have the function of choosing local pictures. Winphone does not support
<input type="file" accept="images/*" />
<input type="file" accept="video/*" />
  • Events and Styles of Screen Rotation
//JS processing
function orientInit(){
    var orientChk = document.documentElement.clientWidth > document.documentElement.clientHeight?'landscape':'portrait';
    if(orientChk =='lapdscape'){
        //Here are the events that need to be executed under the horizontal screen
    }else{
        //Here are the events that need to be executed under the vertical screen
    }
}

orientInit();
window.addEventListener('onorientationchange' in window?'orientationchange':'resize', function(){
    setTimeout(orientInit, 100);
},false)    

//CSS processing
//Vertical screen style
@media all and (orientation:portrait){   }
//Horizontal screen style
@media all and (orientation:landscape){   }
  • audio and video elements cannot be automatically played in ios and andriod
//Audio, Writing 1
<audio src="music/bg.mp3" autoplay loop controls>Your browser doesn't support it yet.</audio>

//Audio, Writing II
<audio controls="controls"> 
    <source src="music/bg.ogg" type="audio/ogg"></source>
    <source src="music/bg.mp3" type="audio/mpeg"></source>
    //Preferred to play music bg.ogg, not support playing bg.mp3
</audio>

//JS Binding Play Automatically (Play Music When Operating Windows)
$(window).one('touchstart', function(){
    music.play();
})

//Compatibility Processing under Wechat
document.addEventListener("WeixinJSBridgeReady", function () {
    music.play();
}, false);

//Summary
//1. The autoplay attribute of the audio element is not available on IOS and Android, and is normal on the PC side.
//2. When the audio element does not set controls, the IOS and Android will occupy the space size, while Chrome on the PC side will not occupy any space.
  • Gravity Induction Event
// Using the device Motion of HTML5 to invoke gravity induction events
if(window.DeviceMotionEvent){
    document.addEventListener('devicemotion', deviceMotionHandler, false)
}   

var speed = 30;
var x = y = z = lastX = lastY = lastZ = 0;
function deviceMotionHandler(eventData){
    var acceleration = event.accelerationIncludingGravity;
    x = acceleration.x;
    y = acceleration.y; 
    z = acceleration.z;
    if(Math.abs(x-lastX)>speed || Math.abs(y-lastY)>speed || Math.abs(z-lastZ)>speed ){
        //Here is the method to be performed after shaking. 
        yaoAfter();
    }
    lastX = x;
    lastY = y;
    lastZ = z;
}

function yaoAfter(){
    //do something
}

//Note: Say yao.js in the shaking effect of the case
  • Wechat Browser Users Adjust Font Size and Page Shrinkage, How to Prevent Users from Adjusting Font Size
//The following code can make Android pages no longer be forced to resize by user font zooming, but there will be a delay of about 1S, during which you can consider loading to deal with.
if (typeof(WeixinJSBridge) == "undefined") {
    document.addEventListener("WeixinJSBridgeReady", function (e) {
        setTimeout(function(){
            WeixinJSBridge.invoke('setFontSizeCallback', { 'fontSize':0}, function(res){
                alert(JSON.stringify(res));
            })
        }, 0)
    });
}else{  
    setTimeout(function(){
        WeixinJSBridge.invoke('setFontSizeCallback', { 'fontSize':0}, function(res){
            alert(JSON.stringify(res));
        })
    }, 0)   
}

//Under IOS, you can use - webkit-text-size-adjust to prohibit users from adjusting font sizes
body { -webkit-text-size-adjust:100%!important; }

//Best solution: Re or percentage layout is best
  • Location pit
//fixed location
//1. Fixed elements under IOS are easy to locate errors. When a soft keyboard pops up, it will affect the location of fixed elements.
//2. Fixed performance under Android is better than iOS. When a soft keyboard pops up, it will not affect the location of fixed elements.
//3. position:fixed is not supported under iOS4
//Solution: Use [Iscroll](http://cubiq.org/iscroll-5), such as:
<div id="wrapper">
        <ul>
               <li></li>
               .....
        </ul>
</div>
<script src="iscroll.js"></script>
<script>
    var myscroll;
    function loaded(){
        myscroll=new iScroll("wrapper");
    }
    window.addEventListener("DOMContentLoaded",loaded,false);
</script>


//position positioning
//When the soft keyboard pops up under Android, it affects the absolute element location
//Solution:
var ua = navigator.userAgent.indexOf('Android');
if(ua>-1){
    $('.ipt').on('focus', function(){
        $('.css').css({'visibility':'hidden'})
    }).on('blur', function(){
        $('.css').css({'visibility':'visible'})
    })
}
  • Playing video incomplete screen
<!--
1.ios7+Support automatic playback
2.Support Airplay Equipment (e.g. speakers, Apple TV)play
x-webkit-airplay="true" 
3.Playing video incomplete screen
webkit-playsinline="true" 
-->
<video x-webkit-airplay="true" webkit-playsinline="true" preload="auto" autoplay src="http://"></video>
  • JS Judgment Equipment
function deviceType(){
    var ua = navigator.userAgent;
    var agent = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];    
    for(var i=0; i<len,len = agent.length; i++){
        if(ua.indexOf(agent[i])>0){         
            break;
        }
    }
}
deviceType();
window.addEventListener('resize', function(){
    deviceType();
})
  • JS Judges Wechat Browser
function isWeixin(){
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=='micromessenger'){
        return true;
    }else{
        return false;
    }
}
  • android 2.3 bug
//1.@-webkit-keyframes need to start at 0% and end at 100%. 0% can't be removed.
//2.after and before pseudo-classes cannot use animation
//3.border-radius does not support% units. To be compatible, you can set radius a larger value.
//4. Writing translate percentages together with scale can lead to failure, for example:
-webkit-transform: translate(-50%,-50%) scale(-0.5, 1)
  • android 4.x bug
// 1. Samsung Galaxy S4's own browser does not support border-radius abbreviation
 // 2. When border-radius and background color are set at the same time, the background color will overflow beyond the corner.
// 3. Some mobile phones (such as Samsung), a link supports mouse: visited event, that is to say, the text becomes purple after link access.
// 4.android cannot play multi-audio audio at the same time
  • Eliminate transition Flash Screen
.css {
    -webkit-transform-style: preserve-3d;
    -webkit-backface-visibility: hidden;
    -webkit-perspective: 1000;
}
  • Turn on hardware acceleration
//Currently, hardware acceleration is supported by Chrome/Filefox/Safari/IE9+, as well as the latest version of Opera, which automatically opens when certain CSS rules are applied to a DOM element, thus resolving page blinking and ensuring smooth animation.
.css {
    -webkit-transform: translate3d(0,0,0);
    -moz-transform: translate3d(0,0,0);
    -ms-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
}
  • Rendering optimization
// 1. Prohibit the use of iframe (blocking the parent document onload event)
// 2. Do not use gif pictures to achieve loading effect (reduce CPU consumption, improve rendering performance)
// Use CSS3 code instead of JS animation;
// Open GPU acceleration;
// Use base64-bit encoding for pictures (large pictures are not recommended for large ones)
    // For some small icons, base64-bit encoding can be used to reduce network requests. However, it is not recommended to use large maps, which consumes CPU. The advantages of small icons are:
    // 1. Reduce HTTP requests;
    // 2. Avoid cross-domain files;
    // 3. The amendment shall take effect in time;
  • Tencent plan
var autoScale = function(){
    var ratio = 320/504,   //This is the aspect ratio of the design draft (504 is the height of the Iphone and the height of the title bar is removed)
        winW = document.getElement.clientWidth,
        winH = document.getElement.clientHeight,
        ratio2 = winW/winH,
        scale;
    if(ratio<ratio2){
        scale = (winH/504).toString().substring(0, 6);
    }else{
        scale = (winW/320).toString().substring(0, 6);  
    }
    var cssText = '-webkit-transform: scale('+scale+');-webkit-transform-origin: top; opacity:1;'  
    $('.wrap').attr('style', cssText);
}
setTimeout(function(){
    if(document.documentElement.clientWidth/document.documentElement.clientHeight !== 320/504){
        autoScale();
    }else{
        $('.page').css({'opacity': 1});
    }
}, 300)  //Add a certain length of time to ensure that width and height are correctly obtained
window.addEventListener('onorientationchange' in window?'orientationchange':'resize', autoScale, false){
        detectOrientatioin();
}   //Switching the horizontal and vertical screen

function detectOrientatioin(){
    if(window.orientation==180 || window.orientation==0){
        //Vertical screen
    }
    if(window.orientation==90 || window.orientation==-90){
        //Horizontal screen
    }
}

Common Mobile Framework

zepto.js
- Official website
- Chinese net
- Browser Detection
- tap incident

Posted by stitchmedia on Sun, 24 Mar 2019 13:51:29 -0700