对齐\ t,冒号和\ t上的文本

时间:2014-12-02 14:51:27

标签: jquery html css

我在<pre>标记中包含以下原始文本,以尽可能多地挽救布局

<pre>

test

field 1 :   Foo
longer field 2  :   Bar
very long field 3   :   FooBar

other text and values

</pre>

字段和值由制表符char(\ t)分隔冒号和制表符char(\ t)。

我想对齐冒号,以便渲染结果为:

test

field 1             :       Foo
longer field 2      :       Bar
very long field 3   :       FooBar

other text and values

到目前为止,我会找到一个jsfiddle here

我对文本没有多少控制权,但是我试图将{t:\ t替换为<span>,所以我得到了一些css样式的控制权,但到目前为止并没有太大的乐趣。

这是我使用的javascript替换\ t:\ t \ t \ tt1:

$('pre').html(
        $('pre')
        .html()
        .split('\t:\t')
        .join('<span class="tab">&nbsp;:&nbsp;</span>'));

并添加了此css规则以浮动<span>

.tab {
    background-color:red;
    width: 10em;
    display: inline-block;
    text-align: right;
    float: left;
}

在每个新行的开头呈现span。我也试过position: absolute无济于事。

我可以选择让冒号对齐吗?

2 个答案:

答案 0 :(得分:10)

使用CSS作为主要驱动程序:

$(document).ready(function() {
    $('pre').html(
        $('pre')
        .html()
        .replace(/(.*)\t:\t(.*)/g,function(_,key,value) {
            return '<div class="row">'+
                '<span class="col">'+key+'</span>'+
                '<span class="col"> : </span>'+
                '<span class="col">'+value+'</span>'+
            '</div>';
        })
    );
});
pre {display:table}
.row {display:table-row}
.col {display:table-cell}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<pre>
    
    test
    
    field 1	:	Foo
    longer field 2	:	Bar
    very long field 3 	:	FooBar
    
    other text and values
    
    </pre>

这里重要的是JavaScript将扫描所需格式的行(key[tab]:[tab]value)并将它们装扮成合适的元素。然后CSS使它们统一。

答案 1 :(得分:9)

好的,所以这实际上非常有趣。

Example fiddle with dynamic width

以下是我们正在做的事情:

<强>的JavaScript

$(document).ready(function() {
    var arr = $('pre').html().split('\n');
    for (var i=0,l=arr.length;i<l;i++){
        if (arr[i].indexOf(':') > -1) {
            var pieces = arr[i].split(':');
            arr[i] = "<span class='left'>" + pieces[0] + "</span>: " + pieces[1];
        }
    }

    $('pre').html(arr.join("\n"));
    var maxWidth = Math.max.apply(null, $('.left').map(function () {
        return $(this).outerWidth(true);
    }).get());
    $('.left').css('width', maxWidth + 15);
});

<强> CSS

.left {
    display: inline-block;
}


JavaScript的解释

我们将基于行而不是冒号分隔您的pre,此处:

var arr = $('pre').html().split('\n');

然后我们正在迭代,寻找:分开:

if (arr[i].indexOf(':') > -1)

如果我们找到一个,我们知道我们需要进行超级花哨的自定义对齐。我们通过拆分:然后将左侧包裹在span中来完成此操作,如下所示:

var pieces = arr[i].split(':');
arr[i] = "<span class='left'>" + pieces[0] + "</span>: " + pieces[1];

然后,我们将修改后的HTML添加回pre并运行这个花哨的小计算以找到最宽的部分:

var maxWidth = Math.max.apply(null, $('.left').map(function () {
  return $(this).outerWidth(true);
}).get());

this answer

无耻地偷走了

然后将最宽的宽度应用于每个左侧元素,并在末尾添加额外的15px填充。

$('.left').css('width', maxWidth + 15);

希望有所帮助!