当前位置:网站首页>Handwritten easy version flexible JS and source code analysis
Handwritten easy version flexible JS and source code analysis
2022-07-04 07:18:00 【Hall owner a Niu】
Personal profile
- Author's brief introduction : Hello everyone , I'm Daniel , New star creator of the whole stack .
- Personal home page : Hall owner a Niu
- Stand by me : give the thumbs-up + Collection ️+ Leaving a message.
- Series column : Hard bubble javascript
- Maxim : To be light , Because there are people who are afraid of the dark !
Catalog
Preface
Our mobile terminal layout usually has rem Combined with the implementation of media query , however , Taobao has such a flexible.js frame , According to width To web pages html The root node has different settings font-size, Greatly improved our development efficiency , Today, Daniel will take you to write a simple version flexible.js And interpret , Understand his general principle .
flexible.js What is it? ?
flexible.js Hand Amoy framework , It is developed by Taobao to adapt to mobile terminals js frame .
The core principle of Amoy framework is based on different width To web pages html The root node has different settings font-size, Then all the distances are used rem Instead of , In this way, screens of different sizes can adapt to the same style .
rem Introduction to adaptive layout
rem ( root em ) It's a relative unit , Be similar to em , em Is the font size of the parent element . The difference is rem The benchmark is relative to htm Font size of element .
such as , Root element ( html ) Set up font - size =12px; Non root element settings width:2rem; Then change to px It means 24px.
rem The advantage is that it can be modified html The size of the text inside changes the size of the elements in the page , Can be controlled as a whole .
Usually in web page layout , We can combine media query +rem Implement element changes , That is, the root corresponding to the screen of different pixels html Style of label font-size The value is different. . Like this :
@media (min-width:860px){
html{
font-size:50px;
}
}
Simple version of flexible.js Source code analysis
(function flexible(window,document){
// obtain html The root element of the
var docEl = document.documentElement;
// dpr Physical pixel ratio window.devicePixelRatio The physical pixel ratio of the current screen will be obtained , If it is pc The end is 1, The mobile terminal is 2.
// If the current browser does not window.devicePixelRatio Then take 1
var dpr = window.devicePixelRatio || 1;
// Set up body Font size of
function setBodyFontSize(){
// If the page has body This element , Is set body Font size of
if (document.body){
document.body.style.fontSize = (12 * dpr) + 'px';
}else{
// otherwise , Waiting for the main page DOM After the element is loaded, set body Font size of
document.addEventListener("DOMContentLoaded",setBodyFontSize);
}
}
setBodyFontSize();
// The core
// Set up html The text size of
function setRemUnit(){
// take html The document width is divided into 10 Equal division , Each is divided into one rem, namely html Of fontsize
var rem = docEl.clientWidth / 10;
docEl.style.fontSize = rem + 'px';
}
setRemUnit();
// When the page size changes , To reset rem Size
window.addEventListener('resize',setRemUnit);
// pageshow The event that triggers the page reload is
window.addEventListener('pageshow',function(e){
if(e.persisted){
// The return is true, It shows that this page is a page from the cache , You also need to recalculate rem Size
setRemUnit();
}
})
// You don't need to know the following
// detect 0.5px supports // Some mobile browsers do not support 0.5 Pixel writing , The following solution enables it to support
if(dpr >= 2){
var fakeBody = document.createElement('body');
var testElement = docunment.createElement('div');
testElement.style.border = '.5px solid transparent';
fakeBody.appendChild(testElement);
docEl.appendChild(fakeBody)
if(testElement.offsetHeight === 1){
docEl.classList.add('hairlines')
}
docEl.removeChild(fakeBody)
}
}(window,document))
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="flexible.js"></script>
</head>
<body>
</body>
</html>
The physical pixel ratio of my Google browser is 1.25
notes :
1.javascript The immediate execution function in :
(function () {}() perhaps (function(){} ())
Immediately execute the function without calling , The second parenthesis can be seen as calling a function . You can give parameters , You can also give anonymous functions function names .
(function sum(a,b){
return a + b;} (1,2))
2.pageshow event
The following three situations will refresh and the face will trigger load event
- a Hyperlinks to tags
- F5 Or the refresh button ( Forced to refresh )
- Forward and backward buttons
But in Firefox , There is a characteristic , There is one “ Round trip caching ”, This cache not only holds page data , And preserved DOM and JavaScript The state of ; In fact, the whole page is saved in memory
So the back button doesn't refresh the page at this time .
You can use pageshow Events to trigger . This event is triggered when the page is displayed , Whether or not it comes from the cache . In the reload page , pageshow Will be in load After the event is triggered ; According to persisted Determine whether it is triggered by the page in the cache pageshow event , Pay attention to this incident window add to .
Conclusion
Use this flexible.js after , You may need to install another cssrem plug-in unit , This plug-in will automatically send your px Convert to rem, Improve development efficiency , Comprehensive, flexible.js Not bad , No need to write media query , And html Of fontsize Is divided , It will always change dynamically with the page size , So as to realize the size change of elements .
If you think the blogger's writing is good , You can pay attention to the current column , Bloggers will finish this series ! You are also welcome to subscribe to other good columns of bloggers .
Series column
Soft grinding css
Hard bubble javascript
The front end is practical and small demo
flask Framework quick start
边栏推荐
- Computer connects raspberry pie remotely through putty
- How to share the source code anti disclosure scheme
- Summary of June 2022
- Introduction to deep learning Ann neural network parameter optimization problem (SGD, momentum, adagrad, rmsprop, Adam)
- Zephyr 学习笔记2,Scheduling
- The crackdown on Huawei prompted made in China to join forces to fight back, and another enterprise announced to invest 100 billion in R & D
- Chain ide -- the infrastructure of the metauniverse
- Review of enterprise security incidents: how can enterprises do a good job in preventing source code leakage?
- 输入年份、月份,确定天数
- What is the use of cloud redis? How to use cloud redis?
猜你喜欢
Valentine's Day is coming! Without 50W bride price, my girlfriend was forcibly dragged away...
the input device is not a TTY. If you are using mintty, try prefixing the command with ‘winpty‘
notepad++如何统计单词数量
Xcode 14之大变化详细介绍
Summary of MySQL common judgment functions!! Have you used it
Deep profile data leakage prevention scheme
Solution of running crash caused by node error
Knowledge payment applet dream vending machine V2
Experience installing VMware esxi 6.7 under VMware Workstation 16
【GF(q)+LDPC】基于二值图GF(q)域的规则LDPC编译码设计与matlab仿真
随机推荐
Cochez une colonne d'affichage dans une colonne de tableau connue
Selection (023) - what are the three stages of event propagation?
How notepad++ counts words
Introduction to rce in attack and defense world
If there are two sources in the same job, it will be reported that one of the databases cannot be found. Is there a boss to answer
Electronic Association C language level 1 34, piecewise function
两年前美国芯片扭捏着不卖芯片,如今芯片堆积如山祈求中国帮忙
com. alibaba. nacos. api. exception. NacosException
socket inet_ pton() inet_ Ntop() function (a new network address translation function, which converts the expression format and numerical format to each other. The old ones are inet_aton(), INET_ ntoa
Master-slave replication principle of MySQL database
Review of enterprise security incidents: how can enterprises do a good job in preventing source code leakage?
在已經知道錶格列勾選一個顯示一列
Responsive mobile web test questions
2022年6月小结
Selenium ide plug-in download, installation and use tutorial
Campus network problems
tornado项目之路由装饰器
Boosting the Performance of Video Compression Artifact Reduction with Reference Frame Proposals and
what the fuck! If you can't grab it, write it yourself. Use code to realize a Bing Dwen Dwen. It's so beautiful ~!
Implementation of ZABBIX agent active mode