Html文件:
<div class="box">........</div>
css文件:
.box {
width: 5rem;
height: 5rem;
background-color: skyblue;
}
Script:
// 拿到html元素
const htmlDom = document.documentElement
// 改变的函数
function serRemFontSize() {
// 拿到屏幕的宽度
const htmlWidth = htmlDom.clientWidth
// 计算fontsize的大小
const htmlFontSize = htmlWidth / 10
// fontsize赋值到html上
htmlDom.style.fontSize = htmlFontSize + 'px'
console.log(htmlWidth);
}
// 第一次进来时主动调用一下
serRemFontSize()
// 实时监听屏幕尺寸改变的函数
window.addEventListener('resize', serRemFontSize)
// 监听页面跳转(前进或者后退),重新设置一下
window.addEventListener('pageshow',function(e){
if (e.persisted) {
serRemFontSize()
}
})
该文章介绍了如何通过JavaScript获取HTML元素,结合CSS设置动态字体大小,以实现基于屏幕宽度的响应式设计。当页面加载、窗口调整大小或页面前进/后退时,会自动调整html元素的font-size属性,确保内容适应不同设备的显示。
622





