Get font-size attribute from style property

烈酒焚心 提交于 2019-12-24 05:49:25

问题


I have a set of paragraph elements

<p style="font-family:Tahoma; font-size:10.666666666666666; margin:0 0 0 0;">
<p style="font-family:Tahoma; font-size:10.666666666666666; margin:0 0 0 0;">
<p style="font-family:Tahoma; font-size:10.666666666666666; margin:0 0 0 0;">
<p style="font-family:Tahoma; font-size:10.666666666666666; margin:0 0 0 0;">

I have to write px after font size degree. I am unable to use my current code

loop
$(this).css("font-size") 

I can't use this because it shows me the font size of the parent div


回答1:


There are two obvious approaches, the first looks at the style attribute searching for the numbers following the font-size: string and replaces that string with itself, though adding px to it:

$('p').attr('style',function(i,s){
    return s.replace(/font-size:\s*(\d+.{0,1}\d*)/, function(a){
        return a + 'px';
    });
});

JS Fiddle demo.

The second alternative is much the same, albeit it directly uses the inline css() method to set the font-size by finding the string font-size:, and the following numbers, then removing the font-size: string (so setting the font-size property to the numbers following that string and adding 'px' to it:

$('p').css('font-size',function(){
    var s = $(this).attr('style').match(/(?:font-size:)s*(\d+.{0,1}\d*)/)[0].replace(/font-size:/,'');
    return s + 'px';
});

JS Fiddle demo.




回答2:


This will read the current value, append "px" to it, and re-assign it back.

$(parent).children('p').each(function(){
    $(this).css("font-size", $(this).css("font-size") + "px");
});


来源:https://stackoverflow.com/questions/15707836/get-font-size-attribute-from-style-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!