jQuery CSS font-family not working with quotes

爱⌒轻易说出口 提交于 2020-01-24 00:19:08

问题


I'm using 2 font-faces and wish to switch between them using jQuery, thing is my font-face's name is 'ArvoBold' and when I use:

css('font-family','ArvoBold') 

it changes to a non-existing font named ArvoBold (no-quotes)! I've tried to make it work with:

css("font-family","'ArvoBold'") 

But it doesn't seem to work. I've also tried to create a variable:

var fontvar="'"+"ArvoBold"+"'";
css('font-family',fontvar);

And also with no success, because on the CSS of the element (checked using Google Chrome's inspector) it keeps using ArvoBold instead of 'ArvoBold'.

Can anybody help me out?

Thanks in advance!

John


回答1:


Not sure of your exact implementation, but this works by escaping the single quotes in the string:

$(".font-face").css("font-family","\'ArvoBold\'");

Why do you need the single quotes?

Quick Test on escaping the single quotes outputs 'ArvoBold' in the content div:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>   
<style>
#content{border:solid 1px red;width:100px;height:100px;text-align:center;}
</style>
</head>

<body>

<div id="content"></div>

<script type="text/javascript">
$(document).ready(function(){
$("#content").html("\'ArvoBold\'");
});
</script>

</body>
</html>



回答2:


You need to define selector and correct your css() brackets.

Here is working jsFiddle.

var fontvar = 'ArvoBold';
$('.mySelector').css({'font-family':fontvar});​

Note: Don't forgot to use $(document).ready() too.




回答3:


In CSS, you can write

font-family: Arial;

as well as

font-family: 'Arial';

and it has the same meaning. It is therefore to be expected that in

'ArvoBold'

the quotes are interpreted as string delimiters and not as a part of the string.

You could try escaping the quotes, i.e.

font-family: "\'ArvoBold\'"

although, I must repeat BoltClock's question: Why do you have quotes in a font name?



来源:https://stackoverflow.com/questions/11903492/jquery-css-font-family-not-working-with-quotes

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