End mobile page development H5 pit Guide

Original link: https://juejin.im/post/5dafc3df5188257a63539c64

Foreword

When the mobile terminal developed H5 usual, we will inevitably encounter various pits, this article will take a look at how we solved a long article, it is recommended to facilitate future access to the collection!

In front of high energy!

canvas in the retina screen blur

Only need to brush can be scaled according to the pixel ratio

run(canvasEl) {
    const canvas = canvasEl;
    const ctx = canvas.getContext('2d');
    const devicePixelRatio = window.devicePixelRatio || 1;
    const backingStorePixelRatio = ctx.webkitBackingStorePixelRatio ||
    ctx.mozBackingStorePixelRatio ||
    ctx.msBackingStorePixelRatio ||
    ctx.oBackingStorePixelRatio ||
    ctx.backingStorePixelRatio || 1;

    const ratio = devicePixelRatio / backingStorePixelRatio;
    if (devicePixelRatio !== backingStorePixelRatio) {
      const oldWidth = canvas.width;
      const oldHeight = canvas.height;

      canvas.width = oldWidth * ratio;
      canvas.height = oldHeight * ratio;

      canvas.style.width = `$px`;
      canvas.style.height = `$px`;
      ctx.scale(ratio, ratio);
    }
  },
复制代码

With the same proportion of the picture is very clear on the PC, but the phone is very vague, because what is it?

The study found that devicePixelRatio mischief, because the phone resolution is too small, according to the resolution to display web pages word is very small, so Apple put the iPhone 4 resolution of 960 640 480 320 only shows a page where this devicePixelRatio = 2; now android chaotic, 1.5 / 2/3, etc., to make more clear image background must be replaced img tag 2x (2x generally are used) in the phone, such as a wide div is a high 100100 , 200,200 have to background, then the background-size: contain ;, such displayed images relatively clear; code as follows:

   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;
复制代码

Enable or disable automatic page recognition of phone numbers;


复制代码

The device will automatically recognize any default may be strings phone number, set up telephone = no to disable this feature set does not recognize the email address and also empathy

h5 website set input type = number of problems

h5 page input of the type set number will generally have three questions:

Question 1: maxlength attribute does not work well


复制代码

Question 2: When the default form submitted by rounding

 //input中type=number一般会自动生成一个上下箭头,点击上箭头默认增加一个step,点击下箭头默认会减少一个step;number中默认step是1,也就是step=0.01可以允许输入2位小数,并且点击上下箭头分别增加0.01和减少0.01;step和min一起使用时数值必须在min和max之间
复制代码

Question 3: Some Android phone problems arise style

Remove the default input method style:

input,textarea {
    border: 0;
    -webkit-appearance: none; //可同时屏蔽输入框怪异的内阴影,解决iOS下无法修改按钮样式,测试还发现,加了此属性后,iOS下默认还是有圆角的,不过可以用border-radius属性修改
}
复制代码

select Settings drop-down selection problem

Question 1: Right-aligned to achieve

Set the following properties

select option {
    direction: rtl;
}
复制代码

Question 2: Disable select the default arrow

::-ms-expand修改表单控件下拉箭头,设置隐藏并使用背景图片来修饰

select::-ms-expand { display:none; }
复制代码

End mobile HTML5 audio autoplay failures

Since the web page automatically play audio or video bad for users or unnecessary traffic consumed, so Apple and Android systems usually prohibit the use of trigger automatic playback and playback JS must be triggered by the user before playing; Solution ideas: first by the user touching the trigger touchstart play and pause (so that the audio starts loading), followed by JS then operate no problem; solving Code:

document.addEventListener('touchstart', function () {
    document.getElementsByTagName('audio')[0].play();
    document.getElementsByTagName('audio')[0].pause();
});
复制代码

CSS animation page white flash, animation Caton, pictures disorder problems

1. The use as synthesis transform and opacity properties designed CSS3 animations, without using the position of the left and top to locate

2. Turn on hardware acceleration

-webkit-transform: translate3d(0, 0, 0);
-moz-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
复制代码

Floating element sub-elements parent distraction height of the box (the BFC)

Solutions are as follows:

1. Parent element to overflow: hidden;

2. parent element to display: inline-block; et

Both methods are provided herein by css property float parent element becomes the BFC (block level format context) elements, the height of the sub-elements can be stretched parent element; however preferable to use a method, as inline-block element itself comes with a number of its own distraction width height

And from the cache problem

Click your browser fallback sometimes does not automatically execute js, especially in mobilesafari; this (bfcache) has a relationship with and from the cache, the solution:

window.onunload = function(){};
复制代码

Positioning pit

In IOS fixed positioned at the top since the soft keyboard will fail, so we use the absolute unity instead of in the development of

audio elements and video elements in ios and playback issues in andriod

 //音频,写法一

复制代码

ios phone system can not play audio / video automatically

This is the default Apple system limitations do not allow autoplay audio / video, you need to tap the trigger play () event to play; then we can play trigger event after page onload:

document.getElementById('music').play();
复制代码

Here generally can play music, if not enough is likely to limit the micro-letter

Question 3: micro message restrictions

If micro-letter limit, then you need to call micro-channel interfaces, the introduction of the first page:


复制代码

JS then write micro-channel events:

document.addEventListener("WeixinJSBridgeReady", function() {
    document.getElementById('music').play();
}, false);
复制代码

summary:

autoplay attribute 1.audio elements not available on IOS and Android, at the end of a normal PC

When 2.audio element is not set controls, in IOS and Android will occupy space, and Chrome on the PC side will not take up any space

Question 4: Safari browser automatically play

document.addEventListener('touchstart', function(){   
    audio.play();
}, false);
复制代码

ios system does not support suspended animation styles (animation-play-state)

H5 page will generally have BGM, will also provide a rotating music icon for the user to open and close the music; we hope that when the position of the icon stops rotating when the user clicks the music button, then point the icon to stop before continuing to run along the animation; animation-play- state is the easiest way, however, does not support ios

The current solution is: Music icon responsible for running the animation, the rotation value of the parent element responsible for recording icon stops

ios prevent long press page element is selected

Solve: Add Style to prevent users from copying, ios and Android in general can be resolved

-webkit-touch-callout:none;  //系统默认菜单被禁用;可以实现页面因为长按弹出各种操作窗口
-webkit-user-select:none; //webkit浏览器  
-khtml-user-select:none; //早期浏览器 
-moz-user-select:none; //火狐 
-ms-user-select:none; //IE10 
user-select:none; 
复制代码

After you add this code there will be problems in the IOS, then found input box is not a typing; for this reason is causing -webkit-user-select: none; this attribute, the solution is in the css file and set it input attributes, as follows:

input {      
     -webkit-user-select:auto; //webkit浏览器    
}
复制代码

When html5 come down Scroll on how Caton / slow Solution

First you could have a page of html and body to increase the height: 100%, then it may cause problems Caton page slide on IOS.

The solution is: 1. Let html body and fixed to 100% (or 100vh), 2. and then put inside a height: 100% div, set overflow-y: auto; and -webkit-overflow-scrolling: touch;

overflow-x: auto in iOS has compatibility issues, the solution:

.scroll-box {
  /* 模态框之类的div不能放在这个容器中,否则关闭模态框有时候关闭不了 */
  height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  overflow-scrolling: touch;
}
复制代码

Click element background or how to remove border

a, button, input, textarea {-webkit-tap-highlight-color: rgba (0,0,0,0); -webkit-user-modify: read-write-plaintext-only; // - webkit-user- modify have side effects, it is no longer capable of inputting a plurality of input characters} or a, button, input, textarea {-webkit-tap-highlight-color: rgba (0,0,0,0);}

Back browser does not refresh

This situation is encountered before, here also said the next; mainly occur in webview in a little more, when the cache hits the back page appear in the form, rather than after the refresh, in many cases this is not your desired results, resolve method is to use js:

window.onpageshow = function(evt){
  if(evt.persisted){ 
     document.body.style.display ="none";
     location.reload();
  }
};
复制代码

onpageshow will trigger each time the page is loaded, whether it is loaded from the cache or normal load, which is the difference between him and the onload; persisted determine whether a page is read out from the cache

Placeholder text position where the input bias on

placeholder where the input text will appear on the positional deviation: PC line-height setting is equal to the end height can be aligned, move to upper end remains, is provided when the solution css line-height:normal;

Clear transition splash screen

-webkit-transform-style: preserve-3d; //设置内嵌的元素在 3D 空间如何呈现:保留3D
-webkit-backface-visibility:hidden; //设置进行转换的元素的背面在面对用户时是否可见:隐藏
-webkit-perspective: 1000;
复制代码

Failure to solve the active pseudo-classes


复制代码

The top status bar background color

apple-mobile-web-app-capable是设置Web应用是否以全屏模式运行;语法:
 //content设置为yesWeb应用会以全屏模式

复制代码

Note: Unless you first use the apple-mobile-web-app-capable specify full-screen mode, otherwise the meta tags will not play any role; if the content is set to default, the status bar is normally displayed; if set to blank, the status bar a black background; if set blank-translucent, the status bar displays the translucent black; if set to default or blank, then the page is displayed below the status bar, the status bar that is occupied by the top portion; page occupies the bottom portion, both without cover or block each other; if set to blank-translucent, the page will fill the screen, which cover the top of the page is a status bar (page overrides 20px height, and iphone4 and itouch4 the Retina screen 40px); default value is the default.

ios Area

IOS in the keyboard for input events keyup / keydown / keypress problems such as poor support

The investigation found that, IOS input method (either native or third-party) can detect English or digital keyup, but not detected in Chinese keyup, after entering the Chinese need only point Backspace key to start the search; the solution is with oninput keyup event of html5 to replace, to achieve a similar effect by keyup codes;

1. Modify the input: CheckBox or input: radio element selected state, checked attributes change

2. Modify the input: text or textarea element values, value property changes

3. Modify the selected item select elements selectedIndex property changes occur unified use input monitor


复制代码

IOS alphabet keyboard input, default capitalized solutions

Set the following properties


复制代码

// three attributes input of autocomplete: The default is on, the representative of whether to allow the browser to automatically record the value of the input can be added in autocomplete in input = "off" to turn off the record and confidential input content; autocapitalize: automatic capitalization; autocorrect: correction

On iOS and OS X font end optimization (horizontal and vertical screen will appear in bold font inconsistencies, etc.) issues

IOS browser will reset when the horizontal screen font size, set the text-size-adjust as none can solve the problem on iOS, but the desktop version of Safari's font scaling function will fail, so the best solution would be for the text-size-adjust 100%

-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
text-size-adjust: 100%;
复制代码

In some cases non-clickable elements such as (label, span) monitor click events will not trigger under ios

Just add a line of code to css element does not trigger the click event of such cases

cursor: pointer;
复制代码

Support for ios time date () is not the same

var date =new Date("2019/10/21"); 
复制代码

2019-10-21 00:00:00 debugging found 2019/10/21 equivalent, that is to say ios default is calculated from zero, we do not need to set the minutes and seconds behind 00:00:00

iOS (safari) bind click event tag is invalid

iOS (safari) sometimes bind a click event tag is invalid, plus empty οnclick = "" like, such as:

ios location.href jump in blank page

In location.href coat layer setTimeout solved!

setTimeout(() => {
       window.location.href = 'www.juejin.im'
}, 0);
复制代码

Keyboard pops up when the whereabouts of bug workaround

In the created hook App.vue's unified treatment can

created() {
    this.handleFocusOut();
    this.handleResize();
},
methods:{
    handleFocusOut() {
      // input 焦点失焦后,ios 键盘收起,但没有触发 window resize,导致实际页面dom仍然被键盘顶上去--错位
      document.addEventListener('focusout', () => {
        document.body.scrollTop = 0;
      });
    },
    // 监听resize事件(键盘弹起触发),然后将 input textarea 元素滑动到可视区域,并将特定元素隐藏
    handleResize() {
      const clientHeight = document.documentElement.clientHeight;
      window.addEventListener('resize', () => {
        // 判断当前 active 的元素是否为 input 或 textarea
        if (
          document.activeElement.tagName === 'INPUT' ||
          document.activeElement.tagName === 'TEXTAREA'
        ) {
          setTimeout(() => {
            // 原生方法,滚动至需要显示的位置
            document.activeElement.scrollIntoView();
          }, 0);
        }

        // 解决键盘弹起后 fixed 定位元素被顶起问题
        const bodyHeight = document.documentElement.clientHeight;
        const ele = document.getElementById('fixed-bottom');
        if (ele) {
          if (clientHeight > bodyHeight) {
            ele.style.display = 'none';
          } else {
            ele.style.display = 'block';
          }
        }
      });
    }
}
复制代码

to sum up

The road is long Come, on a compatible way lopsided

Recommended Service

Guess you like

Origin blog.csdn.net/weixin_45189747/article/details/102723334