我的编辑框cat;dog;pig;tail
中有这样的文字。但我想用';'强调它们在jquery中分隔。字符串应该在editbox中看起来像这种格式。
cat ; dog ; pig ; tail
___ ___ ___ ____
如何在jquery中执行此操作?
<tr id="NameDetails">
<td>
<label for="<%=Names.Animal%>" style="margin-bottom:10px;">Name of Animals:</label>
</td>
<td colspan="2">
<%=Html.TextBox(Names.Animal, String.Empty, new { @class = "AnimalControl FreeText" })%>
</td>
</tr>
答案 0 :(得分:2)
您可以使用jQuery脚本将textarea转换为div并使用单词的跨度填充它。用边框强调跨度。点击并强制关注时将其转换回textarea。
HTML
<textarea class="textarea-underlined">cat ; dog ; pig ; tail</textarea>
的jQuery
// Dynamically provide onBlur support for all newly added textarea elements.
$('body').on('blur','.textarea-underlined',function(e){
e.preventDefault();
// Copy textarea contents to array and split by semi-colon
var contents = $(this).val();
words = contents.split(';');
// Create div and fill with styled spans.
$(this).replaceWith('<div class="pseudo-textarea"></div>');
words.forEach(function(el,index,arr){
$('.pseudo-textarea').append('<span class="underlined">'+el.trim().toString()+'</span>');
if(words.length-1 != index ){
$('.pseudo-textarea').append(";");
}
});
});
// Reverse the whole thing onClick of the div.
$('body').on('click','.pseudo-textarea',function(e){
e.preventDefault();
// Build array.
var contents = new Array();
$.each( $(this).find('span'), function( index, value ){
contents.push( $(value).html() );
});
// Replace div with textarea and fill with array contents separated by semi-colon.
$(this).replaceWith('<textarea id="textarea-underlined" class="textarea-underlined">'+contents.join(' ; ')+'</textarea>');
$('#textarea-underlined').focus();
});
CSS
.underlined {
border-bottom: 1px dashed black; // Your choice: solid, dotted, dashed...
}
.underlined:hover {
border-bottom: 1px dashed red; // Whatever color you want for hover.
}
span {
margin-right: 4px;
margin-left: 4px;
}
// Make the textarea and div look the same.
.pseudo-textarea, textarea {
cursor: text;
font-family: 'Arial';
font-size: 1em;
border: 1px solid #D4D4D4;
padding: 5px;
resize: none;
display: inline-block;
height: 100px; width: 300px;
}
.pseudo-textarea > span:first-child{
margin-left: 1px;
}