gpt4 book ai didi

javascript - 如何将文本包装在两行上,每行的数量相等?

转载 作者:行者123 更新时间:2023-11-29 21:14:43 25 4
gpt4 key购买 nike

我正在一个网站上创建元素框(如果重要,还包括 CodeIgniter、Bootstrap、jQuery),其中的标题通常比框本身长。我将文本包装在框内,因此它会出现在多行中。问题是它在某些情况下看起来仍然很难看。例如,文本“Brand new photo camera Nikon 3600”换行成类似这样的内容:

Brand new photo camera Nikon
3600

相反,我希望它像这样在每一行上更均匀:

Brand new photo
camera Nikon 3600

我可以做出有根据的猜测并在某些地方插入换行符,但应该有更好的方法。主要寻找 CSS 解决方案,但只要它有效,欢迎使用一些 JavaScript/jQuery。谢谢!

最佳答案

我开发了一些 working solution - 它并不完美,但它会找到中间空间并在那里 split 。也就是说,更好的解决方案可能涉及总字符数以找到最接近 true 中心的空间,或者甚至可能获取整行的宽度并将字符串的容器 CSS 设置为一半那个宽度。但是我只有时间...

最终代码

function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;

if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);

if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}

function splitValue(value, index) {
return value.substring(0, index) + "," + value.substring(index);
}

function evenBreak(myString) {
var count = (myString.match(/ /g) || []).length; //How many spaces are there
var middle = Math.ceil(count/2); //Find the middle one

var middleIndex = nth_occurrence(myString, " ", middle); //Get the index of the middle one
var splitString = splitValue(myString, middleIndex).split(","); //Split the string into two pieces at our middle

myString = splitString[0] + "<br>" + splitString[1].substring(1); //Put it back together with a line break between

return myString;
}

var str = evenBreak("This is our newly split string with a line break in the center!");
alert(str);

我们如何到达那里

首先,我们需要找出有多少个空格...

var count = (temp.match(/ /g) || []).length;

现在我们知道有 X 个空间,最中间的是通过做...找到的

var middle = Math.ceil(count/2);

但是我们如何在我们的字符串中找到中间空格呢?这是我从 another question 中抓取的东西做到这一点......

function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;

if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);

if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}

好的,所以我们确切地知道要放置换行符的位置。但是我们需要一个函数来做到这一点。我将在那里拆分字符串并在它们之间放置一个换行符,方法是使用以下函数...

function splitValue(value, index) {
return value.substring(0, index) + "," + value.substring(index);
}

已知问题

  • 这只会 split 一次。它依赖于将字符串分成两半,而不是多次。
  • 如果字符集中度不均匀,字符串将不会被完美分割。它只计算空格,不考虑总字符数。例如,如果您有以下句子“他是一个搞笑的喜剧 Actor ”,那么最中心空间两侧的字符差异很大。

关于javascript - 如何将文本包装在两行上,每行的数量相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39900860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com