textareaで行ごとにナンバリングする

Ads

Result


コード見せたいけどSyntax highlight使うほどじゃない時とかに。gistでいいんじゃ、と言われたらそれまでですが。

jQuery

;(function ( $, window, document, undefined ) {
    'use strict';
 
    var pluginName = 'lineLine',
        defaults = {
            startsFrom: 0,
            className: 'lineline'
        };
     //オプションセッティング
    function Plugin( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options);
 
        this._defaults = defaults;
        this._name = pluginName;
 
        this.init();
    }
 
    Plugin.prototype.init = function () {
        var self = this;
         
        var lines = $(self.element).html().split('\n');
        var lineCount = lines.length;
        //textareaをtableにする
        var html = '<div class="' + self.options.className + '"><table class="' + self.options.className + '-code" border="0" cellspacing="0" cellpadding="0">';
        //ナンバリング
        for (var i = self.options.startsFrom; i < lineCount; i++){
            html += '<tr><td class="' + self.options.className + '-numbers">' + (i + 1) + '</td><td class="' + self.options.className + '-lines">' + lines[i] + '</td></tr>';
        }
        html += '</table></div>';
         
        $(self.element).before(html);
        $(self.element).remove();
    };
 
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                new Plugin( this, options ));
            }
        });
    };
 
})( jQuery, window, document );
//textareaを指定
$('textarea').lineLine();

css

.lineline{
max-height: 300px;
width: 700px;
margin: 50px auto 0;
background: #ececec;
padding: 20px;
overflow: auto;
text-align: left;
}
 
.lineline-numbers   {
width: 20px;
border-right: 1px solid #ccc;
padding-right:
5px; color: #777;
}
.lineline-lines{
padding-left: 20px;
white-space: pre;
white-space: -moz-pre;
white-space: -pre;
white-space: -o-pre;
word-wrap: break-word;
}
.lineline-code{
font-family: 'Consolas';
font-size: 12px;
line-height: 18px;
width: 100%;
white-space: nowrap;
}

html

via

add line number to textarea or code or any dom element lineLine