简体   繁体   中英

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). 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). 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.

Check out this Topic here for example, the 2nd Answer could be a good start for you:

Applying CSS to single characters dynamically?

That might help you find a solution that fits your expectations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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