简体   繁体   中英

Convert non-pixel css value to px

As some measurement parameters in css are not always in px values, how can be such non-pixel value converted to px ?

Let's have

var x = $('#element').css('parameter');

and let's say that the value of such x variable is 1.2em or some other string that contains not just number, but also measurement type information ( px , em , pt , cm , in , ...).

What is all-browser solution to convert such string into integer , having results in px ?

You can use the built-in method getComputedStyle which will interpolate any non- px value into pixels. For example:

var el = document.getElementById('foo'); // has a relative font size

console.log(el.style.fontSize); // "5em"
console.log(window.getComputedStyle(el).fontSize); // "80px"

From there you can convert into an integer.

Example JsBin and MDN Documentation .

$("#element").css("padding","2em")
var value = parseInt($("#element").css("font-size"));
var padding = 2*value ;
console.log(padding);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM