使用 Javascript 修改用户输入的字体系列

Modify Font Family on User Input with Javascript

我希望我的文本区域在用户键入时呈现另一种字体(等宽字体除外)。我的目标是使用 Javascript 来实现这一点。

下面是一个用于将用户输入更改为大写(实时)的脚本。但是,我无法通过使用以下脚本作为模板找到问题的解决方案。


    <div id="thoughts-textarea">
      <label for="thoughts">Additional thoughts?</label><br>
      <textarea name="thoughts" id="thoughts" cols="30" rows="5" 
      placeholder="Enter any comments here..."></textarea>
    </div>

<script>
  document.addEventListener('DOMContentLoaded', function(){
  let thoughts = document.getElementById("thoughts");
  thoughts.addEventListener('input', fontFam);
});

function fontFam(ev){
  let num = ev.charCode;
  let letter = String.fromCharCode(num);
  console.log(ev.type, num, letter, ev.target.value);
  ev.target.value = ev.target.value.toUpperCase();
}
</script>

例如我试过拼接...

function fontFam(ev){
  let num = ev.charCode;
  let letter = String.fromCharCode(num);
  console.log(ev.type, num, letter, ev.target.style);
  ev.target.style = ev.target.style.fontFamily = "Nunito, sans-serif";
}

function fontFam(ev){
  let num = ev.charCode;
  let letter = String.fromCharCode(num);
  console.log(ev.type, num, letter, ev.target.style);
  ev.target.style = ev.target.style.font = "Nunito, sans-serif";
}

function fontFam(ev){
  let num = ev.charCode;
  let letter = String.fromCharCode(num);
  console.log(ev.type, num, letter, ev.target.value.style);
  ev.target.value.style = ev.target.value.style.font = "Nunito, sans-serif";
}

...以及其他多种变体,但仍然找不到可行的解决方案。

感谢您的时间和努力,

马利克

p.s。这是我的第二个post。抱歉,如果我还没有学会正确的程序(对于 javascript & SO posts。)

您需要创建一个 FontFace 并将 FontFamily 应用于正文 您还需要创建一个函数,只要用户单击按钮更改字体,该函数就会执行。例如。 changeFont(fontName)

async function changeFont(fontName, fontUrl, options={}) {
    const ff = new FontFace(fontName, `url(${fontUrl})`, options);
    try {
     const loadedFont = await ff.load()
     document.fonts.add(loadedFont)
     document.body.style.fontFamily = fontName
    } catch (err) {
     console.error(err)
    }
}

然后你就可以像这样使用函数了

await changeFont('Junction Regular', 'fonts/junction-regular.woff', { style:'normal', weight: 700' })

你非常接近,请参阅下面我更新的代码段:

document.addEventListener('DOMContentLoaded', function(){
  let thoughts = document.getElementById("thoughts");
  thoughts.addEventListener('input', fontFam);
});

function fontFam(ev){
  let num = ev.charCode;
  let letter = String.fromCharCode(num);
  console.log(ev.type, num, letter, ev.target.value);
  ev.target.style.fontFamily = "Impact,Charcoal,sans-serif";
}
<div id="thoughts-textarea">
  <label for="thoughts">Additional thoughts?</label><br>
  <textarea name="thoughts" id="thoughts" cols="30" rows="5" placeholder="Enter any comments here..."></textarea>
</div>

我在示例中使用了 impact 字体系列,但对于您的代码,我只需进行调整:

ev.target.value.style = ev.target.value.style.font = "Nunito, sans-serif";

收件人:

ev.target.value.style.font = "Nunito, sans-serif";