How can i get default font size in pixels by using JavaScript or JQuery?

前端 未结 9 1451
Happy的楠姐
Happy的楠姐 2021-02-04 09:07

As you know em is a relative font measurement where one em is equal to the height of the letter \"M\" in the default font size. An advantage in using it is because you will be a

相关标签:
9条回答
  • 2021-02-04 09:54

    This works in FF.

    <script>
    function getStyle(el,styleProp)
    {
        var x = document.getElementById(el);
        if (x.currentStyle)
            var y = x.currentStyle[styleProp];
        else if (window.getComputedStyle)
            var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
        return y;
    }
    
    function GetSt()
    {
        var font_size = getStyle("div2","fontSize"); 
        alert ( font_size );
    }
    
    </script>
    <div id="div1" style="height: 100px;font-size: 20px;">
    <div id="div2" style="font-size: 2em;">
    test
    </div>
    </div>
    <button onclick="GetSt();">Click</button>
    
    0 讨论(0)
  • 2021-02-04 09:57

    Although it seems like getting the default font size might be a good idea -- if it's to set the layout of your pages and such, it's probably a safer practice to just let the user handle that.

    If they have their font size larger - it's because they're blind and vice versa. I'd recommend setting your defaults and 'recommending' a resolution/size. Unless your app depends on it -- let the user handle it.

    0 讨论(0)
  • 2021-02-04 09:59

    One trick I've seen/used in the past is to render some text (say 50 arbitrary characters, or Ms) and then measure the size of the rendered container and do the math to figure out the height and width of a single character. Is this what you're going for? You can do the rendering in the background so the user doesn't see it.

    0 讨论(0)
提交回复
热议问题