【问题标题】:Additional quotes added for font-family value while applying CSS应用 CSS 时为 font-family 值添加了额外的引号
【发布时间】:2020-03-17 06:04:35
【问题描述】:

我正在尝试通过以下代码为 span 标签动态应用 font-family CSS。

    var node = document.getElementsByTagName("span"); 
    $(node).css("font-family","Courier New,Courier,monospace");

在执行此操作时,font-family 的第一部分被包裹在双引号中,如下所示

"font-family: "Courier New", Courier, monospace;"

样式应用于元素,但我需要删除为 font-family value("Courier New") 的第一部分添加的内部双引号,以便在控制器端处理此 HTML。

Jsfiddle 链接:http://jsfiddle.net/uot92ysf/9/

谁能建议我如何在没有这个内引号的情况下为 span 标签应用 font-family 样式,或者如何在添加 CSS 后删除这个引号?

问候,

基尔塔纳。

【问题讨论】:

  • 我不这么认为。那是你不能那样做的模式。
  • 是否有理由删除引号?在 W3C 标准中,您必须为非通用字体系列名称提供有效的字体系列名称值:drafts.csswg.org/css-fonts-3/#font-family-prop

标签: javascript jquery css font-family


【解决方案1】:

我认为你的报价没有更多的影响。只需阅读文档

https://mathiasbynens.be/notes/unquoted-font-family

【讨论】:

    【解决方案2】:

    来自 MDN:<family-name> Values

    字体系列的名称。例如,“Times”和“Helvetica”是字体系列。 应引用包含空格的字体系列名称

    【讨论】:

      【解决方案3】:

      var node = document.getElementsByTagName("span"); 
      $(node).css("font-family",`'Courier New,Courier,monospace'`);
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <span>Example</span>

      您可以将属性添加为 String 对象以解决此问题。

      【讨论】:

        【解决方案4】:

        'Courier New' 周围的单引号就可以了。示例:

        编辑:

        根据示例在 CSS 中设置字体系列时,它是双引号的。根据 CSS 标准。 “字体系列名称必须作为字符串引用,或者作为一个或多个标识符的序列不加引号。这意味着每个标记开头的大多数标点字符和数字必须在不带引号的字体系列名称中进行转义。”

        因此,它的工作方式与我在 CSS JS Fiddle Example 中设置它的方式相同

        $('#button2').click(function() {
            var node = document.getElementById("test"); 
        
            var font = 'Courier New'; 
        
        console.log($(node).css("background-color")  );
        if ( $(node).css("background-color") == "rgb(255, 255, 255)")  {
                $(node).css("background-color", "rgb(255, 0, 0)");
                    $(node).css("font-family", font);
            } else {
                $(node).css("background-color", "rgb(255, 255, 255)");
                    $(node).css("font-family", "Arial");
            }
        });
        

        原始回复

        $('#button2').click(function() {
            var node = document.getElementsByTagName("span"); 
            $(node).css("font-family","'Courier New',Courier,monospace");
        });
        
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-05
        • 2015-09-10
        • 2017-02-27
        • 1970-01-01
        • 2011-09-16
        • 2014-09-19
        • 2018-11-30
        相关资源
        最近更新 更多