如何获取内联样式中指定的字体大小

How to get font size specified in inline style

下面的代码打印出无效的字体大小:Chrome 中的 16pt。 如何解决此问题以便返回内联样式中指定的相同字体大小 12pt?

<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

    <script>
        $(function () {
            var css = $('#_QNU0OVBMB').css(["font-size"]);
            alert(css["font-size"]);
        });
    </script>

</head>
<body>
    <div id="_QNU0OVBMB" style="font-size:12pt">
        m.FIRMA
    </div>

警报以 PIXELS 为单位显示尺寸,16px = 12pts

Pixel to point converter

它说的不是 16pt,而是 16px,这就是 chrome 呈现该指令的方式。点通常只适用于印刷媒体,如果你使用像素,它应该按预期工作。

jQuery.css() methodreturns计算风格属性.

由于您想要获取内联样式属性中指定的值,您可以直接访问元素 style property 上的 fontSize 属性 以获得 12pt.

var element = document.getElementById('_QNU0OVBMB'),
    fontSize = element.style.fontSize;

alert(fontSize); // 12pt
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="_QNU0OVBMB" style="font-size:12pt">
  m.FIRMA
</div>

同样,对于 jQuery,您只需要访问 jQuery 对象中的 DOM 元素:

var fontSize = $('#_QNU0OVBMB')[0].style.fontSize;

alert(fontSize); // 12pt
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="_QNU0OVBMB" style="font-size:12pt">
  m.FIRMA
</div>

当您想要覆盖它们时,请尝试使用 !important。 12pt = 16px。

<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

    <script>
        $(function () {
            var css = $('#_QNU0OVBMB').css(["font-size"]);
            alert(css["font-size"]);
        });
    </script>

</head>
<body>
    <div id="_QNU0OVBMB" style="font-size:12px!important">
        m.FIRMA
    </div>