javascript - 如何在里面对齐部分文本
问题描述
如何在两行选择中对齐部分文本?
我需要将两行与每行中相同数量的字符对齐。每行以字符“|”结尾 对齐。例子:
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>";
解决方案
要正确对齐,您可以为此定义一个 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>
推荐阅读
- javascript - 使用 css 和 javascript 构建的滚动鼠标的边框动画
- python - 字符串输出不正常
- webos - 将我的 mysql 数据库与我的 tv lg 的 webOS 应用程序链接
- mongodb - 如何将两个单独的 Mongo 聚合组合成一个聚合?
- c - 在 C 程序中使用 shell 命令还是编写将使用某种形式的 C 代码的 shell 脚本更好?
- angular - 如何在 ngStyle 中为特定项目使用 ngFor 索引?
- node.js - 有没有办法在 EJS 中使用本机浏览器函数 fetch?
- linux - 如何将流程执行记录为汇编指令?
- azure - 如何将我的 Azure VM DNS 重定向到我的注册域?
- cakephp - 将禁用的下拉元素添加到 INSERT 语句中