2017-02-23 97 views
0

我试图在正在受到键控函数影响的div中插入下划线或空白区域。目标是能够移动文本中的空白处。 keyup函数工作正常,插入空格(div类下划线)不是。用div在div中插入HTML

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>'); 
} 
}); 

}); 
+0

你能进一步扩大:“我们的目标是能够移动其中的空白空间在文中“。你究竟是什么意思? – roger

+0

我打算让用户能够选择他们希望空白处在文本中的位置。 – Dustin

回答

0

所以使用SUBSTR获得所剩下的剩余的文本长度和文本之后添加它。

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>

并可根据您的评论

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>

+0

这将是一个正确的想法,除非它是一个要求空白空间停留在那里,不要被文本吃掉。 – Dustin

+0

所以空白只是移动?因此,将字符串在x和Y处分开并放在那里。 text.substr(0,X)+ blank + text.substr(X) – epascarello

+0

基本上,是的。这个想法是让用户实时预览文本中的空白位置 – Dustin