简体   繁体   English

通过附加和前置空格在javascript函数中自动换行和居中对齐

[英]wrap text and center align in javascript function by appending & prepending spaces

for (eg) for a max 15 Word Line, if the input str="text acknowledgement" the the string should contain str =" text acknowledgement" basically adding spaces at the right place so that when i place in a 15 line Word Wrapping editor it should wrap and center align as shown below. 对于(例如)最多15个字行,如果输入str =“ text Confirmation”,则该字符串应包含str =“ =” confirmation“,基本上在正确的位置添加空格,以便当我放置在15行的Word Wrapping编辑器中时它应该环绕并居中对齐,如下所示。

text 文本
acknowledgement 致谢

I am seeing a solution here Wrap Text In JavaScript except it doesn't center align the words. 我在这里看到一个解决方案, 在JavaScript中将文本换行,除了它不会使单词居中对齐。

Any help is appreciated. 任何帮助表示赞赏。

Aligning text by inserting space characters works ONLY in a very restricted environment: fixed-width horizontal space using a monospace font of a specific, known size. 通过插入空格字符对齐文本仅在非常受限的环境中起作用:使用特定的已知大小的等宽字体的固定宽度水平空格。 Change any of those parameters (width, font, font-size) and your alignment will be off. 更改任何这些参数(宽度,字体,字体大小),您的对齐方式将关闭。

Alignment should be accomplished with CSS. 对齐应使用CSS完成。

Here is my solution: 这是我的解决方案:

String.prototype.centerText = function(numberOfSpaces)
{
    var text = this;
    text = text.trim();
    var l = text.length;
    var w2 = Math.floor(numberOfSpaces / 2);
    var l2 = Math.floor(l / 2);
    var s = new Array(w2 - l2 + 1).join(" ");
    text = s + text + s;
    if (text.length < numberOfSpaces)
    {
        text += new Array(numberOfSpaces - text.length + 1).join(" ");
    }
    return text;
};

Usage: 用法:

var textToBeCentered = "Hello, World!";
var centeredText = textToBeCentered.centerText(40);
// centeredText = "              Hello, World!              ";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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