jQuery / JavaScript:以简单的方式将像素转换为em

我正在寻找一种简单的方法来为我的插件添加一行代码,将几个像素值转换为em值,因为我的项目布局需要在ems中。 有没有一种简单的方法可以做到这一点,因为我不想在网站上添加第三方插件。

不会在这里发布代码,因为它与它自己的插件无关。

谢谢。

示例:13px – > ?? em

我认为你的问题非常重要。 由于显示分辨率的类别正在迅速增加,因此使用em定位来支持各种屏幕分辨率是一种非常吸引人的方法。 但无论你多么努力地保留所有内容 – 有时你可能从JQuery拖放或从另一个库获得像素值,并且你希望在将它发送回服务器以进行持久化之前将其转换为em。 这样下次用户查看页面时,项目将处于正确的位置 – 无论他们使用的设备的屏幕分辨率如何。

当您可以查看代码时,JQuery插件并不是非常可怕,特别是如果它们像这个插件一样短而甜,可以根据需要将像素值转换为em 。 事实上它太短了我会在这里粘贴整个东西。 有关版权声明,请参阅链接。

$.fn.toEm = function(settings){ settings = jQuery.extend({ scope: 'body' }, settings); var that = parseInt(this[0],10), scopeTest = jQuery('
 
').appendTo(settings.scope), scopeVal = scopeTest.height(); scopeTest.remove(); return (that / scopeVal).toFixed(8) + 'em'; }; $.fn.toPx = function(settings){ settings = jQuery.extend({ scope: 'body' }, settings); var that = parseFloat(this[0]), scopeTest = jQuery('
 
').appendTo(settings.scope), scopeVal = scopeTest.height(); scopeTest.remove(); return Math.round(that * scopeVal) + 'px'; };

用法示例: $(myPixelValue).toEm();$(myEmValue).toPx();

我刚刚在我的应用程序中对此进行了测试,效果很好。 所以我想我分享。

以下似乎按照您的要求执行,但它基于父级的font-size ,以及元素本身,在px中返回:

 function px2em(elem) { var W = window, D = document; if (!elem || elem.parentNode.tagName.toLowerCase() == 'body') { return false; } else { var parentFontSize = parseInt(W.getComputedStyle(elem.parentNode, null).fontSize, 10), elemFontSize = parseInt(W.getComputedStyle(elem, null).fontSize, 10); var pxInEms = Math.floor((elemFontSize / parentFontSize) * 100) / 100; elem.style.fontSize = pxInEms + 'em'; } } 

JS小提琴概念certificate 。

笔记:

  • 如果您尝试转换为em的元素是body ,则该函数返回false,但这是因为我无法确定将值设置为1em是否合理,或者只是不管它。

  • 它使用window.getComputedStyle() ,因此如果没有一些调整,它将无法与IE一起使用。

参考文献:

  • Math.floor()
  • parentNode
  • parseInt()
  • tagName
  • toLowerCase()
  • window.getComputedStyle()

像素和ems基本上是不同类型的单位。 你不能简单地在它们之间进行转换。

例如,在顶级标题设置为200%字体大小的网站上,默认字体大小为16px的用户,1em可能等于32px。 将标题移动到文档中的其他位置,可以是64px或16px。 将同一文档提供给其他用户,可能是30/60 / 15px。 开始谈论一个不同的元素,它可以再次改变。

最接近你想要的是从像素转换为ems +文档+上下文+设置。 但是如果有人要求你用ems布置你的项目,他们可能不会很高兴你试图以像素为单位进行“转换”。

老问题,但作为参考,这里是我拼凑在一起的东西,范围和后缀是可选的。 将它作为字符串传递给rem或em值,例如。 ‘4em'[你可以使用空格和大写/小写],它将返回px值。 除非你给它一个范围,它将是查找本地EM值的目标元素,它将默认为body,有效地为你提供rem值。 最后,可选的后缀参数[boolean]会将“px”添加到返回的值,例如48变为48px。

例如: emRemToPx( '3em', '#content' )

在字体大小为16px / 100%的文档上返回48

 /** * emRemToPx.js | @whatsnewsisyphus * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. * see CC0 Public Domain Dedication . */ var emRemToPx = function( value, scope, suffix ) { if (!scope || value.toLowerCase().indexOf("rem") >= 0) { scope = 'body'; } if (suffix === true) { suffix = 'px'; } else { suffix = null; } var multiplier = parseFloat(value); var scopeTest = $('
 
').appendTo(scope); var scopeVal = scopeTest.height(); scopeTest.remove(); return Math.round(multiplier * scopeVal) + suffix; };

通常,当您想将px转换为em ,转换会在元素本身上进行。 getComputedStyle返回px中的值,这会破坏它们的响应能力。 以下代码可用于帮助解决此问题:

 /** * Get the equivalent EM value on a given element with a given pixel value. * * Normally the number of pixel specified should come from the element itself (eg element.style.height) since EM is * relative. * * @param {Object} element - The HTML element. * @param {Number} pixelValue - The number of pixel to convert in EM on this specific element. * * @returns {Boolean|Number} The EM value, or false if unable to convert. */ window.getEmValueFromElement = function (element, pixelValue) { if (element.parentNode) { var parentFontSize = parseFloat(window.getComputedStyle(element.parentNode).fontSize); var elementFontSize = parseFloat(window.getComputedStyle(element).fontSize); var pixelValueOfOneEm = (elementFontSize / parentFontSize) * elementFontSize; return (pixelValue / pixelValueOfOneEm); } return false; }; 

使用它就像下面这样简单:

 var element = document.getElementById('someDiv'); var computedHeightInEm = window.getEmValueFromElement(element, element.offsetHeight); 

我已将此function打包到库中,完成参数类型检查: px-to-em

鉴于此HTML:

 

Hello World!

你可以期待这些输出:

 pxToEm(16, message) === 1 pxToEm(24, message) === 1.5 pxToEm(32, message) === 2 

由于OP要求在没有库的情况下执行此操作,我已将px-to-em的源代码复制到现场演示中:

 function pxToEm (px, element) { element = element === null || element === undefined ? document.documentElement : element; var temporaryElement = document.createElement('div'); temporaryElement.style.setProperty('position', 'absolute', 'important'); temporaryElement.style.setProperty('visibility', 'hidden', 'important'); temporaryElement.style.setProperty('font-size', '1em', 'important'); element.appendChild(temporaryElement); var baseFontSize = parseFloat(getComputedStyle(temporaryElement).fontSize); temporaryElement.parentNode.removeChild(temporaryElement); return px / baseFontSize; } console.log(pxToEm(16, message), 'Should be 1'); console.log(pxToEm(24, message), 'Should be 1.5'); console.log(pxToEm(32, message), 'Should be 2'); 
 

Hello World!

无论如何,Ems不等于像素。 它们是相对测量。

 This is 1em font size, which means the text is the same size as the parent This is 1.5em font size, which means the text is 150% the size as the parent 

基本大小由用户代理(浏览器)确定。

检查这个小脚本: https : //github.com/normanzb/size

只要传入参考dom元素,它就可以帮助您转换单位

Interesting Posts