2014-03-06 116 views
0

我在我的編輯框中輸入了這樣的文字,cat;dog;pig;tail。但我想用''來強調它們;用jquery分開。該字符串應該在editbox中看起來像這種格式。如何在jquery中加下劃線文字

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

編輯框?是一個textarea?打字時顯示下劃線? – SajithNair

+2

這可能是可能的,但你應該發佈一些努力.. –

+0

嗨,它的編輯框。不需要在打字時我不需要。一旦焦點移出編輯框我希望他們得到下劃線 – Naruto

回答

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

http://jsfiddle.net/X8934/5/

+0

嗨它的工作,但除非我點擊外,我不能編輯帶下劃線的字符串,我也需要該編輯功能。這樣做嗎? – Naruto

+0

而不是'border-bottom',你不能使用'text-decoration:underline;'? – Bharadwaj

+0

@Bharadwaj You coul d做文字修飾,但是這個例子顯示了一個間距在下面的虛線。我想我從字面上理解了它的外觀。風格走! – SacWebDeveloper