Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
In a recent H5 page development, the page uses absolute positioning or percentage, VH, VH to layout the soft keyboard compression page, found that the page will affect the page layout when clicking the input box below on the mobile terminal:
- When the soft keyboard is invoked, the page is compressed;
- After the above problem is solved, the page is compressed again after the input box starts to input text.
Fix the height of the page as soon as you enter the page, first get the height of the browser viewable area, and then assign the height to the root div of the page.
var hrt = document.body.clientHeight;
<section className="game-room" id="gameRoom" style={{ height: winh + "px" }}>
Copy the code
Solution to problem 2: Judge the size of window.onresize, indirectly judge the soft keyboard to pop up, and process the page layout, such as changing position or setting the easy size to a fixed value.
- Get the initial viewport size, then store it in localStorage or some other localStorage, then set it to the outermost container size, and then set the layout internally as a percentage.
var winh = document.body.clientHeight;
window.localStorage.setItem("curwinh", winh);
Copy the code
- Listen for window.onresize. The outermost container is always the same height as the viewport, regardless of whether there is a soft keyboard.
window.onresize = function () {
var newh = window.localStorage.getItem("curwinh");
document.getElementById("app").style.height = newh + "px";
}
Copy the code
If there are other style changes when the soft keyboard pops up and down, you can use the following code:
var clientHeight = document.documentElement.clientHeight || document.body.clientHeight; window.onresize = function () { var nowClientHeight = document.documentElement.clientHeight || document.body.clientHeight; If (clientHeight > nowClientHeight) {document.getelementById ("input-box").style.background = Document.getelementbyid ("input-box").style. Background = '#ecf6fd'}}Copy the code
This solves the problem of page compression when typing text!
Related extension: Input in mobile ios, the cursor disappears or is misplaced when the focus is obtained.
-webkit-user-select:none Causes that the input box cannot be entered in iOS and the cursor does not appear. The setting is as follows:
user-select: text; -webkit-user-select: text;
Copy the code
Use scrollIntoView to make the current element appear in the specified position, so as not to misplace the cursor:
e.target.scrollIntoView(true);
e.target.scrollIntoViewIfNeeded();
Copy the code