我一直在为我设计的可变字体编写这段代码,每输入一个字母,字体的重量就会变得更重。
如果我有一个输出,它可以正常工作,但是是否可以在输入测试区域字段中输入每一个字母时直接更改字体大小?
<html>
<body>
<div class="myInput" id="testarea" contentEditable="true"> insert text </div>
<style>
@import {
https: //static.wixstatic.com/ufonts/5bda5f_2acfb8a9fc2d407896ec287713383a8d/woff2/file.woff2}
@font-face {
font-family:wf_2acfb8a9fc2d407896ec287713383a8d;
src: url("https://static.wixstatic.com/ufonts/5bda5f_2acfb8a9fc2d407896ec287713383a8d/woff2/file.woff2") format("woff2");
font-weight: 101 900
}
div {
font-family: 'wf_2acfb8a9fc2d407896ec287713383a8d', sans-serif;
font-weight: 101;
font-size: 100px;
}
</style>
<script>
let initWeight = 100;
document.getElementById("testarea").onkeypress = function(event) {
myFunction(event.key)
};
function myFunction(letter) {
innerHTML = '<span style="font-weight:' + initWeight + '">' + letter + '</span>'
document.getElementById("testarea").innerHTML += innerHTML
initWeight += 10;
}
</script>
</body>
</html>
这是我先前的代码,其中的输出被更改了:
<html>
<style>
@import {
https: //static.wixstatic.com/ufonts/5bda5f_04476cfbcbfe4a349a33e0080a539b44/woff2/file.woff2}
@font-face {
font-family:wf_04476cfbcbfe4a349a33e0080;
src: url("https://static.wixstatic.com/ufonts/5bda5f_04476cfbcbfe4a349a33e0080a539b44/woff2/file.woff2") format("woff2");
font-weight: 101 900
}
div {
font-family: 'wf_04476cfbcbfe4a349a33e0080', sans-serif;
font-weight: 101;
font-size: 100px;
}
</style>
<body>
<div class="myInput" id="testarea" contentEditable="true"> insert text </div>
<div id="result" contentEditable="true"></div>
<script>
let initWeight = 100;
document.getElementById("testarea").onkeypress = function(event) {
myFunction(event.key)
};
function myFunction(letter) {
const letterHTML = '<span style="font-weight:' + initWeight + '">' + letter + '</span>'
document.getElementById("result").innerHTML += letterHTML
initWeight += 10;
}
</script>
</body>
</html>
发布于 2020-12-04 08:33:15
我不太确定,但我想你是在找这样的东西(?)
<h4>Type here</h4>
<div class="myInput" id="testarea" contentEditable="true"></div>
<span></span>
JavaScript
const inputDiv = document.getElementById('testarea');
const span = document.querySelector('span');
let weight = 0;
inputDiv.onkeydown = function(e) {
weight += 100;
this.style.fontWeight = weight;
span.textContent = weight;
}
span
标记用于测试。
看看这个JSFiddle
https://stackoverflow.com/questions/65139348
复制相似问题