简体   繁体   中英

How to underline text in jquery

i have text like this in my editbox, cat;dog;pig;tail . but i want to underline them with ';' separated in jquery. the string should look like this format in editbox.

cat ; dog ; pig ; tail
___   ___   ___   ____

How to do this in 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>

You could use a jQuery script to convert a textarea to a div and fill it with spans of the words. Underline the spans with borders. Converting it back to a textarea on click and force focus.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM