简体   繁体   中英

How to put white space after a letter while typing with JavaScript?

I want to put empty spaces after a letter while typing.

We can make it with css letter-spacing property but when we copy this text, i does not keep white spaces.

How can we make it with vanilla javascript?

Added letter-spacing to my css to show what i want exaclty.

JSFIDDLE

 var my_text = document.getElementById("my_text"); var output_text = document.getElementById("output_text"); my_text.addEventListener("keyup", function() { var val = this.value; output_text.innerHTML = val; }); 
 #output_text { width: 300px; height: 200px; border: 1px solid #ccc; letter-spacing: 10px; } 
 <textarea id="my_text" cols="30" rows="10"></textarea> <div id="output_text"></div> 

Split all the characters and join with a white space: https://jsfiddle.net/wkw72u7e/4/ .

var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");

my_text.addEventListener("keyup", function() {
  output_text.innerHTML = this.value.split('').join(' ');
});


#output_text {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
}

And why vanilla javascript? Ordinary javascript can do it:

 var my_text = document.getElementById("my_text"); var output_text = document.getElementById("output_text"); my_text.addEventListener("keypress", function(event) { event.preventDefault(); output_text.innerHTML += " " + String.fromCharCode(event.keyCode); }); 
 #output_text { width: 300px; height: 200px; border: 1px solid #ccc; } 
 <textarea id="my_text" cols="30" rows="10"></textarea> <div id="output_text"></div> 

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