简体   繁体   English

如何更改每个输入的字母 javascript 的字体粗细

[英]How to change font weight for each letter typed javascript

I have this variable font that I made and I want to implement it on a website, where when the user types the font weight for each letter grows.我有我制作的这个可变字体,我想在一个网站上实现它,当用户键入每个字母的字体权重时,它会增加。 I have this code right now that it grows for the whole text typed, but everything changes there, not each letter (so what I need the code to do is say for each keydown the font weight changes but not the whole text, so the first letter typed would have the smaller font weight and stay that way but the following letters would grow in font weight).我现在有这个代码,它会随着输入的整个文本而增长,但是那里的一切都发生了变化,而不是每个字母(所以我需要代码做的是说每个 keydown 字体粗细都会改变,但不是整个文本,所以第一个键入的字母将具有较小的字体粗细并保持这种状态,但以下字母的字体粗细会增加)。 Thanks in advance for anyone who can help out I'm really new to this!!提前感谢任何可以提供帮助的人,我对此真的很陌生!

<p id="testarea" contentEditable="true">
   Type your text hereeeeeeeeeee
</p>

<button type="button" onclick="myFunction2()">uncensour</button>

<script>
   document.getElementById("testarea").onkeypress = function () { 
   myFunction() }
   document.getElementById("testarea").addEventListener("input", myFunction);
   var initWeight = 101;
   function myFunction() {
      document.getElementById("testarea").style.fontWeight = initWeight++ ;
   }
   function myFunction2() {
      document.getElementById("testarea").style.fontWeight = "101";
   }


   function myFunction2() {
      document.getElementById("testarea").style.fontWeight = "101";
   }
</script>

As far as im aware there is sadly no real way to style individual characters in the same element.据我所知,遗憾的是没有真正的方法可以在同一元素中设置单个字符的样式。 Therefore you probably need to split up the typed text into the individual characters and wrap them in an element (Span for example).因此,您可能需要将输入的文本拆分为单个字符并将它们包装在一个元素中(例如 Span)。 So you have each Character in a different element that you can individually style.因此,您可以将每个角色都放在一个可以单独设置样式的不同元素中。 For doing that you need a bit of JS and should probably just play around with those approaches until you are Happy.为此,您需要一些 JS,并且可能应该只使用这些方法,直到您满意为止。

Check out this Topic here for example, the 2nd Answer could be a good start for you:例如,在此处查看此主题,第二个答案对您来说可能是一个好的开始:

Applying CSS to single characters dynamically? 将 CSS 动态应用于单个字符?

That might help you find a solution that fits your expectations.这可能会帮助您找到符合您期望的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM