简体   繁体   中英

Insert HTML in Div with a substr

I am trying to insert an underline or blank space in a div that is being affected with a keyup function. The objective is to be able to move where the blank space is in the text. The keyup function works fine, the inserting of the blank space (div class underline) isnt.

HTML:

<div class="bigwhitecard" id="bigwhitecard"></div>

<textarea id="text" placeholder="Type your card here" name="text"></textarea>

Javascript/Jquery:

$(document).ready(function () {
$('#text').keyup(function(){
  $('#bigwhitecard').html($(this).val());
});

var blankplace = 0;

$('#rightbtn').click(function() {
blankplace++;
});

$('#leftbtn').click(function() {
blankplace--;
});

var b = '<div class="underline"></div>';

$('#bigwhitecard').each(function() {
var blankplace = 0;

var txt = $(this).text();
if (txt.length>0) {
    $(this).html(''+txt.substring(0,blankplace)+'<div class="underline">       </div>');
}
});

 });

So use a substr to get the remaining text length that is left over and add it after the text.

 var filler = "__________"; var out = document.getElementById("bigwhitecard"); document.getElementById("text").addEventListener("keyup", function() { var txt = this.value, placeholder = txt.length<filler.length ? '<span class="underline">' + filler.substr(0,filler.length-txt.length) + '</span>' : ''; out.innerHTML = txt + placeholder; }); 
 .underline { text-decoration: underline } 
 <div class="bigwhitecard" id="bigwhitecard"></div> <textarea id="text" placeholder="Type your card here" name="text"></textarea> 

And based on your comment

 var out = document.getElementById("bigwhitecard"); document.getElementById("text").addEventListener("keyup", function() { var txt = this.value, ind = 6, len = this.value.length, pre = len > ind ? txt.substr(0,ind) : txt, suf = len > ind ? txt.substr(ind) : ""; out.innerHTML = pre + "<span>_</sapn>" + suf; }); 
 .underline { text-decoration: underline } 
 <div class="bigwhitecard" id="bigwhitecard"></div> <textarea id="text" placeholder="Type your card here" name="text"></textarea> 

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