简体   繁体   English

当字体名称有空格时如何使用 JQuery 设置 CSS 字体系列

[英]How to set a CSS font-family using JQuery when the font name has a space

I'm trying to set the font-family property using the JQuery css method and running into a problem when the font name has a space.我正在尝试使用 JQuery css方法设置font-family属性,并在字体名称有空格时遇到问题。

No matter how I quote or don't quote the font name, the element ends up like:无论我如何引用或不引用字体名称,元素最终都会像:

<h1 style="font-family: "Comic Sans"">Title Text</h1>

with nested double quotes.带有嵌套的双引号。

 var font_family = 'Arial Black'; var $title_template = $('<h1>Title Text</h1>'); var $title; console.log(font_family) $title = $title_template.clone().css({'font-family': font_family}); $('body').append($title) font_family = "'Arial Black'"; console.log(font_family); $title = $title_template.clone().css({'font-family': font_family}); $('body').append($title) font_family = '"Arial Black"'; console.log(font_family); $title = $title_template.clone().css({'font-family': font_family}); $('body').append($title)
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1 style="font-family: 'Arial Black'">Title Text</h1>

If you are looking at the font in the developer options in your browser, don't be alarmed that it looks like poorly nested quotes: <h1 style="font-family: "Arial Black"">Title Text</h1> .如果您正在浏览器的开发人员选项中查看字体,请不要担心它看起来像是嵌套不好的引号: <h1 style="font-family: "Arial Black"">Title Text</h1> That's just how the browser chooses to render the Style property of that element.这就是浏览器选择呈现该元素的 Style 属性的方式。 The style is actually being applied, and the font family is being set properly.实际上正在应用样式,并且正在正确设置字体系列。

If you look at the properties of the DOM element (in Chrome DevTools for example), you'll see that the value of font-family is "Arial Black" .如果您查看 DOM 元素的属性(例如在 Chrome DevTools 中),您会看到 font-family 的值为"Arial Black" The extra quotes are there because of the space in the font name.由于字体名称中有空格,因此存在额外的引号。 And if you change the first line of your JS from var font_family = 'Arial Black to var font_family = 'Arial' , the value of font-family will appear simply as Arial (without quotes).如果您将 JS 的第一行从var font_family = 'Arial Black更改为var font_family = 'Arial' ,则 font-family 的值将简单地显示为Arial (不带引号)。

PS - To get "Comic Sans" to appear I had to use "Comic Sans MS", the proper name of the infamous font. PS - 为了让“Comic Sans”出现,我必须使用“Comic Sans MS”,这是臭名昭著的字体的专有名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM