使用jQuery更改字体系列

时间:2015-08-24 16:40:26

标签: jquery

我试图弄清楚为什么这不起作用:

$(document).ready(function() {
   if (fontPreference === "MavenPro") {
       $("*").css('font-family', '"Maven Pro" !important');
   }
});

我有必要的样式表来保存字体...我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

问题是jQuery在使用.css()时不理解!important属性,而是可以使用.attr()。像这样:

$(document).ready(function() {
    $( "#selectionTest" ).change(function() {
        var fontPreference = $( "#selectionTest" ).val();
        $("body").attr('style', 'font-family:"'+fontPreference+'" !important');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testing">
    <p>This is the tekst that we will be testing on</p>
    <p style="color: red;">This p has inline styling</p>
    <select id="selectionTest">
        <option value="arial">arial</option>
        <option value="verdana">verdana</option>
        <option value="Comic Sans MS">comic sans</option>
        <option value="Mavenpro">Mavenpro</option>
    </select>
</div>

答案 1 :(得分:0)

&#13;
&#13;
$(document).ready(function() {

  $("#setfont").click(function() {
    $("body").append("<style>* { font-family:  monospace!important;}</style>");
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="javascript:void(0);" id="setfont">Set font</a>

<p>Some text</p>
&#13;
&#13;
&#13;