How can I get the font size of an element as it was set by css

后端 未结 4 1640
慢半拍i
慢半拍i 2020-12-09 20:10

I\'m writing a simple jQuery that to change the font size of an element by a certain percentage. The problem I\'m having is that when I get the size with jQuery\'s $(\'#el\'

相关标签:
4条回答
  • 2020-12-09 20:40

    i had this problem once. i use this function to get the int value of a css attribute, if there is one.

    function PBMtoInt(str)
    { 
    return parseInt(str.replace(/([^0-9\.\-])+/,"")!=""?str.replace(/([^0-9\.\-])+/,""):"0");
    }
    
    0 讨论(0)
  • 2020-12-09 20:41

    In Chrome:

    var rules = window.getMatchedCSSRules(document.getElementById('target'))
    

    returns a CSSRuleList object. Need to do a bit more experimentation with this, but it looks like if m < n then the CSSStyleRule at rules[n] overrides the one at rules[m]. So:

    for(var i = rules.length - 1; i >= 0; --i) {
        if(rules[i].style.fontSize) {
            return /.*(em|ex|ch|rem|vh|vw|vmin|vmax|px|in|mm|cm|pt|pc|%)$/.exec(rules[i].style.fontSize)[1];
        }
    }
    

    In Firefox, maybe use sheets = document.styleSheets to get all your stylesheets as a StyleSheetList, then iterate over each CSSStyleSheet sheet in sheets. Iterate through the CSSStyleRules in sheet (ignoring the CSSImportRules) and test each rule against the target element via document.getElementById('target').querySelector(rule.selectorText). Then apply the same regexp as above..... but that's all just a guess, I haven't tested it out or anything....

    0 讨论(0)
  • 2020-12-09 20:48

    All of your target browsers with the exception of IE will report to you the "Computed Style" of the element. In your case you don't want to know what the computed px size is for font-size, but rather you want the value set in your stylesheet(s).

    Only IE can get this right with its currentStyle feature. Unfortunately jQuery in this case works against you and even gets IE to report the computed size in px (it uses this hack by Dean Edwards to do so, you can check the source yourself).

    So in a nutshell, what you want is impossible cross-browser. Only IE can do it (provided you bypass jQuery to access the property). Your solution of setting the value inline (as opposed to in a stylesheet) is the best you can do, as then the browser does not need to compute anything.

    0 讨论(0)
  • 2020-12-09 20:56

    This jQuery plugin looks like it will do the trick:

    Update: jQuery Plugin for Retaining Scalable Interfaces with Pixel-to-Em Conversion

    Github: jQuery-Pixel-Em-Converter

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