search
HomeWeb Front-endJS TutorialExample of js implementing rem automatic matching and calculation of font-size

This article mainly introduces the example of automatic rem matching and calculation of font-size in js. The editor thinks it is quite good. Now I will share the js source code with you and give you a reference. If you are interested in js, please follow the editor to take a look.

During the actual development process, we are often confused by various width and height calculations. Especially using the rem calculation method, adaptive layout stumps a large number of programmers. In order to solve this kind of problem, I think you can use js to monitor screen width changes to change the value of the HTML root element font-size.

The following is the implementation code related to JavaScript:

(function (doc, win) {
  var docEl = doc.documentElement,
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
    recalc = function () {
      var clientWidth = docEl.clientWidth;
      if (!clientWidth) return;
      if(clientWidth>=640){
        docEl.style.fontSize = '100px';
      }else{
        docEl.style.fontSize = 100 * (clientWidth / 640) + 'px';
      }
    };
  if (!doc.addEventListener) return;
  win.addEventListener(resizeEvt, recalc, false);
  doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

This code selects 640px as the base value. Why choose 640?

The page width is 640px It is a safe maximum width, ensuring that there will be no white space on both sides of the mobile page. Note that px here is a CSS logical pixel, which is different from the physical pixel of the device. For example, the iPhone 5 uses a Retina screen, and uses a device pixel of 2px x 2px to represent a css pixel of 1px x 1px, so the device pixel number is 640 x 1136px, and its CSS logical pixel number is 320 x 568px.
So when you want to switch to the mobile page, you need to scale the width of the rendering to 640px.

For example, when the width of a p on the page is 60 and the height is 65, you can directly write the style like this:

{
  width:0.6rem;
  height:0.65rem
}

Browser compatibility

rem is a newly introduced measurement unit in CSS3. Everyone will definitely feel frustrated and worried about browser support. In fact, there is no need to be afraid. You may be surprised that there are quite a few supported browsers, such as: Mozilla Firefox 3.6+, Apple Safari 5+, Google Chrome, IE9+ and Opera11+. It's just that poor IE6-8 can't, so just treat them as transparent. I've always been like this.

However, when using units to set fonts, you cannot completely ignore IE. If you want to use this REM, but also want to be compatible with the effect under IE, you can consider using "px" and "rem" together. Use "px" to achieve the effect under IE6-8, and then use "Rem" to achieve the effect of the browser. Just let IE6-8 not change with the change of text. Who makes this Ie6-8 so old? It's quite interesting if you don't want to try it. Maybe this will become the mainstream unit of measurement.

Complete example code:

<!DOCTYPE html>
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
   <meta content="telephone=no" name="format-detection" />
   <meta name="format-detection" content="email=no" />
   <meta http-equiv="Cache-Control" content="no-cache"/>
 <title>响应式布局</title>
 <style>
  html{font-size: 20px;width: 100%;height: 100%;}
  body{margin: 0;padding: 0;}
  header,footer{width: 100%;background: #17A578;color: #fff;font-size:1rem;text-align: center;line-height: 2rem;}
  .footer{position: fixed;bottom: 0;}
  .box{}
  .public{width: 5rem;height: 5rem;font-size: 1.2rem;display: inline-block;text-align: center;color: #fff;line-height: 5rem;margin-top: 1rem;}
  .left{background: #f00;}
  .center{background: #048F74;}
  .right{background: #000;}
 </style>
 </head>
 <body>
 <header>页面头部</header>
 <p class="box">
  <p class="public left">左</p>
  <p class="public center">中</p>
  <p class="public right">右</p>
  <p class="public left">左</p>
  <p class="public center">中</p>
  <p class="public right">右</p>
 </p>
 <footer class="footer">页面底部</footer>
  <script>
    //orientationchange方向改变事件
    (function (doc, win) {
     var docEl = doc.documentElement,//根元素html
     //判断窗口有没有orientationchange这个方法,有就赋值给一个变量,没有就返回resize方法。
      resizeEvt = &#39;orientationchange&#39; in window ? &#39;orientationchange&#39; : &#39;resize&#39;,
      recalc = function () {
       var clientWidth = docEl.clientWidth;
       if (!clientWidth) return;
       //把document的fontSize大小设置成跟窗口成一定比例的大小,从而实现响应式效果。
       docEl.style.fontSize = 20 * (clientWidth / 320) + &#39;px&#39;;
      };
      //alert(docEl)
     if (!doc.addEventListener) return;
     win.addEventListener(resizeEvt, recalc, false);//addEventListener事件方法接受三个参数:第一个是事件名称比如点击事件onclick,第二个是要执行的函数,第三个是布尔值
     doc.addEventListener(&#39;DOMContentLoaded&#39;, recalc, false)//绑定浏览器缩放与加载时间
    })(document, window);
    //alert(document.documentElement.clientWidth/320)

  </script>
 </body>
</html>

The above is the entire content of this article, I hope it will be helpful to everyone's learning! !

Related recommendations:

The most complete JavaScript learning summary

Sharing better solutions for JavaScript experience asynchronous

How to use regular expressions to highlight JavaScript code

The above is the detailed content of Example of js implementing rem automatic matching and calculation of font-size. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

20+道必知必会的Vue面试题(附答案解析)20+道必知必会的Vue面试题(附答案解析)Apr 06, 2021 am 09:41 AM

本篇文章整理了20+Vue面试题分享给大家,同时附上答案解析。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)