问题描述
我希望我的文本区域在用户键入时呈现另一种字体(除了等宽字体)。我的目标是使用 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,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,ev.target.style);
ev.target.style = ev.target.style.font = "Nunito,ev.target.value.style);
ev.target.value.style = ev.target.value.style.font = "Nunito,sans-serif";
}
...以及其他多种变体,但仍然找不到可行的解决方案。
感谢您的时间和努力,
马利克
附言这是我的第二篇文章。如果我还没有学习正确的程序(对于 javascript 和 SO 帖子),我深表歉意。
解决方法
您非常接近,请参阅下面我更新的片段:
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";
您需要创建一个 FontFace 并将 FontFamily 应用到 body
您还需要创建一个函数,每当用户单击按钮更改字体时都会执行该函数。例如。 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' })