摘要:本篇教程通过代码讲解了jQuery如何获取rem的值会丢失小数点后面的px大小,希望阅读本篇文章以后大家有所收获,帮助大家对jQuery的理解更加深入。
计算方法,精度损失来自于浏览器将rem转成px的过程。
element.currentStyle ? element.currentStyle : window.getComputedStyle(element, null)
可以获取px小数点后的数值
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" /> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <title></title> <style type="text/css"> .c { width: 1.345rem; } </style> </head> <body> <div> </div> <script type="text/javascript"> function getElementStyle(selector) { var element = document.querySelector(selector); return element.currentStyle ? element.currentStyle : window.getComputedStyle(element, null); } function getElementStyleValue(selector, cssAttr, isRem) { var fontSize = parseFloat(getElementStyle('html').fontSize), elementStyle = getElementStyle(selector); value = parseFloat(elementStyle[cssAttr]), isRem != false?isRem = true:''; if(isRem) { value = (value/fontSize).toFixed(4) + "rem"; } else { value = value.toFixed(4)+"px"; } console.log(value); return value; } var value1 = getElementStyleValue('.c', 'width'); var value2 = getElementStyleValue('.c', 'width', false); console.log(value1,value2); </script> </body> </html>
本文由职坐标整理发布,欢迎关注职坐标WEB前端jQuery频道,获取更多jQuery知识!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号