当前位置:网站首页>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
边栏推荐
- A new understanding of how to encrypt industrial computers: host reinforcement application
- Knowledge payment applet dream vending machine V2
- window上用.bat文件启动项目
- Status of the thread
- Node connection MySQL access denied for user 'root' @ 'localhost' (using password: yes
- 输入年份、月份,确定天数
- Introduction to spark core components
- Set JTAG fuc invalid to normal IO port
- Computer connects raspberry pie remotely through putty
- 提升复杂场景三维重建精度 | 基于PaddleSeg分割无人机遥感影像
猜你喜欢
flask-sqlalchemy 循环引用
Su Weijie, a member of Qingyuan Association and an assistant professor at the University of Pennsylvania, won the first Siam Youth Award for data science, focusing on privacy data protection, etc
NLP literature reading summary
Node connection MySQL access denied for user 'root' @ 'localhost' (using password: yes
Bottom problem of figure
The important role of host reinforcement concept in medical industry
[Flink] temporal semantics and watermark
Vulhub vulnerability recurrence 77_ zabbix
Introduction to deep learning Ann neural network parameter optimization problem (SGD, momentum, adagrad, rmsprop, Adam)
Status of the thread
随机推荐
Unity 从Inspector界面打开资源管理器选择并记录文件路径
[kubernetes series] kubesphere is installed on kubernetes
Introduction to spark core components
[web security] nodejs prototype chain pollution analysis
Bottom problem of figure
[FPGA tutorial case 8] design and implementation of frequency divider based on Verilog
Selenium driver ie common problem solving message: currently focused window has been closed
云Redis 有什么用? 云redis怎么用?
【Kubernetes系列】Kubernetes 上安装 KubeSphere
Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg
请问旧版的的常用SQL怎么迁移到新版本里来?
flask-sqlalchemy 循环引用
Set JTAG fuc invalid to normal IO port
2022-021ARTS:下半年開始
How to buy financial products in 2022?
电子协会 C语言 1级 34 、分段函数
[Android reverse] function interception (use cache_flush system function to refresh CPU cache | refresh CPU cache disadvantages | recommended time for function interception)
Zabbix agent主动模式的实现
js 常用时间处理函数
com. alibaba. nacos. api. exception. NacosException