2017-02-23 98 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