首页 > 解决方案 > 如何在里面对齐部分文本

问题描述

如何在两行选择中对齐部分文本?

我需要将两行与每行中相同数量的字符对齐。每行以字符“|”结尾 对齐。例子:

Lorem Ipsum alternative | other text
Lorem Ipsum             | other text
$strdocumento="Lorem Ipsum alternative";
$strdocumento=str_pad($strdocumento, 50, '!', STR_PAD_RIGHT)."***";
$strdocumento=str_replace("!"," ",$strdocumento);

echo $strdocumento."|<br>";

//Line 2

$strdocumento="Lorem Ipsum ";
$strdocumento=str_pad($strdocumento, 50, '!', STR_PAD_RIGHT)."***";
$strdocumento=str_replace("!"," ",$strdocumento);

echo $strdocumento."|<br>";

标签: javascriptphphtml

解决方案


要正确对齐,您可以为此定义一个 div 和一个 css 样式

echo '<div class="alignRight">'.$strdocumento.'|</div>';

css

div.alignRight{
  text-align:right;
  width: 15ch;//to place same number of characters in a line 
  display: block;
  float:;//you can add any css style to it and it works
}

编辑 我知道它不是完美的答案,因为Option元素不能有任何子元素,但你总是可以选择替代/伪选择 插件

如果您想在选择中执行此操作而不伪造它,那么这是我的代码

只有当字体是等宽字体时它才能正常工作(http://en.wikipedia.org/wiki/Monospaced_font

<style type="text/css">
select { font-family: 'Courier',serif; }
</style>

在js脚本上面定义select,这样就可以识别select

<select id="mySelect"></select>

现在在这里将所有变量放在一个数组中,并找到最长字符串的长度直到字符 - “|” 并用最长的字符串减去其他字符串以添加那么多空格

<script type="text/javascript">

    // var string1 = '<?php //echo $strdocumento_1;?>';
    // var string2 = '<?php //echo $strdocumento_2;?>';
    var string1 = 'Lorem Ipsum alternative | Other Text';
    var string2 = 'Lorem Ipsum | Other Text';
    //you can use for loop or while loop in your php

    var arrToFindLengthOfLongestString = [string1.substr(0, string1.indexOf('|')), string2.substr(0, string2.indexOf('|'))];

    var longestLength = arrToFindLengthOfLongestString.sort(function (a, b) { return b.length - a.length; })[0].length;

    for (var i = 0; i < arrToFindLengthOfLongestString.length; i++) {
        for (var j = arrToFindLengthOfLongestString[i].length; j <= longestLength; j++) {
            arrToFindLengthOfLongestString[i]=arrToFindLengthOfLongestString[i]+"\xa0";
        }
        arrToFindLengthOfLongestString[i] = arrToFindLengthOfLongestString[i]+"|";
        // alert(arrToFindLengthOfLongestString[i]);
    }

    var arrForOption = [{
        text: arrToFindLengthOfLongestString[0]+'your other text',//you can use loop if there are more variables
        value: 'your value'
    }, {
        text: arrToFindLengthOfLongestString[1]+'your other text',//
        value: 'yourvalue'
    }];


var select = document.getElementById('mySelect');

// Iterate over array
arrForOption.forEach(function (obj, i) {
    // Create new <option> with dynamic value and text
    // Add the <option> to the <select>
    select.appendChild(new Option(obj.text, obj.value));
});
</script>

推荐阅读