【问题标题】:Get font-size attribute from style property从样式属性获取字体大小属性
【发布时间】:2013-03-20 10:12:51
【问题描述】:

我有一组段落元素

<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;">

字体大小后我必须写px。我无法使用我当前的代码

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

我不能使用它,因为它显示了父 div 的字体大小

【问题讨论】:

  • 如果后面没有单位(px、pt等),浏览器将忽略字体大小。
  • 是的,帕提克·戈萨尔。这是主要问题。我需要写 px 以获得正确的字体大小。

标签: jquery font-size


【解决方案1】:

这将读取当前值,将“px”附加到它,然后重新分配。

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

【讨论】:

  • 不正确,因为它显示了父 div 的字体大小。
  • parent 必须是包含这些 p 标签的元素。为什么不直接在任何输入数字的脚本中打印“px”?
【解决方案2】:

有两种明显的方法,第一种是查看style 属性,搜索font-size: 字符串后面的数字,然后用它自己替换该字符串,尽管在其中添加px:

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

JS Fiddle demo.

第二个选择几乎相同,尽管它直接使用内联css()方法通过找到字符串font-size:和以下数字来设置font-size,然后删除font-size:字符串(所以设置将font-size 属性添加到该字符串后面的数字并添加“px”:

$('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.

【讨论】:

  • 其实我也做过类似的事情。谢谢。
猜你喜欢
  • 2019-01-31
  • 2011-11-02
  • 2018-12-08
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多