簡體   English   中英

如何在jquery中為文本加下划線

[英]How to underline text in jquery

我的編輯框中有這樣的文字, 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>

您可以使用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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM