Вопрос по javascript, dom, css, events – Преобразование em в px в Javascript (и получение размера шрифта по умолчанию)

47

Error: User Rate Limit ExceededemError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceededdefault font sizeError: User Rate Limit Exceededem значение к точномуpxError: User Rate Limit Exceeded

Этот ответError: User Rate Limit Exceeded

Since ems measure width you can always compute the exact pixel font size by creating a div that is 1000 ems long and dividing its client-Width property by 1000. I seem to recall ems are truncated to the nearest thousandth, so you need 1000 ems to avoid an erroneous truncation of the pixel result.

Error: User Rate Limit Exceeded

function getDefaultFontSize(parentElement)
{
    parentElement = parentElement || document.body;
    var div = document.createElement('div');
    div.style.width = "1000em";
    parentElement.appendChild(div);
    var pixels = div.offsetWidth / 1000;
    parentElement.removeChild(div);
    return pixels;
}

Error: User Rate Limit ExceededemError: User Rate Limit ExceededpxError: User Rate Limit Exceeded

Math.round(ems * getDefaultFontSize(element.parentNode))

Problem:Error: User Rate Limit ExceededgetDefaultFontSizeError: User Rate Limit ExceededDOESError: User Rate Limit ExceededoffsetWidthError: User Rate Limit ExceededdivError: User Rate Limit ExceededoffsetWidthError: User Rate Limit ExceededonpropertychangeError: User Rate Limit ExceededDOMSubtreeModifiedError: User Rate Limit Exceeded

Question:Error: User Rate Limit ExceededgetDefaultFontSize()Error: User Rate Limit Exceeded

Error: User Rate Limit Exceededfont-size-checkError: User Rate Limit Exceeded Randy the Dev
Error: User Rate Limit Exceeded mgiuffrida

Ваш Ответ

4   ответа
6

em.

Place this div anywhere in your HTML code

<div id="div" style="height:0;width:0;outline:none;border:none;padding:none;margin:none;"></div>

Place this function in your JavaScript file

var em;
function getValue(id){
    var div = document.getElementById(id);
    div.style.height = 1em;
    em = div.offsetHeight;
}

'getValue'em

3

Number(getComputedStyle(document.body,null).fontSize.replace(/[^\d]/g, ''))

 Number(  // Casts numeric strings to number
   getComputedStyle(  // takes element and returns CSSStyleDeclaration object
     document.body,null) // use document.body to get first "styled" element
         .fontSize  // get fontSize property
          .replace(/[^\d]/g, '')  // simple regex that will strip out non-numbers
 ) // returns number
Error: User Rate Limit Exceeded
22

Edit: No, there isn't.

Error: User Rate Limit Exceeded

parseFloat(getComputedStyle(parentElement).fontSize);

Error: User Rate Limit ExceededError: User Rate Limit Exceeded.

Edit:

Error: User Rate Limit ExceededparentElement.currentStyle["fontSize"]Error: User Rate Limit ExceededpxError: User Rate Limit Exceeded

Error: User Rate Limit ExceededactualError: User Rate Limit Exceeded2emError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededparseFloatError: User Rate Limit ExceededparseFloat(getComputedStyle(parentElement, "").fontSize)Error: User Rate Limit ExceededNumberError: User Rate Limit ExceededNaNError: User Rate Limit Exceeded.matchError: User Rate Limit ExceededNumberError: User Rate Limit ExceededparseFloat.
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededNumber()?
1

const singleEmInPixels = getSingleEmInPixels();
console.log(`1em = ${singleEmInPixels}px`);

/**
 * returns the amount of pixels for a single em
 */
function getSingleEmInPixels() {
    let low = 0;
    let high = 200;
    let emWidth = Math.round((high - low) / 2) + low;
    const time = performance.now();
    let iters = 0;
    const maxIters = 10;
    while (high - low > 1) {
        const match = window.matchMedia(`(min-width: ${emWidth}em)`).matches;
        iters += 1;
        if (match) {
            low = emWidth;
        } else {
            high = emWidth;
        }
        emWidth = Math.round((high - low) / 2) + low;
        if (iters > maxIters) {
            console.warn(`max iterations reached ${iters}`);
            break;
        }
    }
    const singleEmPx = Math.ceil(window.innerWidth / emWidth);
    console.log(`window em width = ${emWidth}, time elapsed =  ${(performance.now() - time)}ms`);
    return singleEmPx;
}

Похожие вопросы