gpt4 book ai didi

javascript - 需要将字符串拆分为字符并与容器对齐

转载 作者:数据小太阳 更新时间:2023-10-29 05:36:13 24 4
gpt4 key购买 nike

产地

origin

结果

result

我想把一个字符串拆分成一个字符,并且让每个字符都平等地适合容器,这是我暂时的工作:http://jsfiddle.net/d5fu9/

第一项必须附加到左侧,最后一项必须附加到右侧。

  $.fn.textjustify = function() {
return this.each(function() {
var text = $(this).text(),
containerWidth = $(this).width(),
character = '',
string = '',
singleWidth = 0,
firstItemWidth = 0,
lastItemWidth = 0,
alignWidth = 0;

if ('' !== text) {
$(this).css('position', 'relative');
textArray = text.split('');
singleWidth = Math.floor(containerWidth / textArray.length);

for (i in textArray) {
// Wrapp with div to get character width
character = ('' === $.trim(textArray[i])) ? '&nbsp' : textArray[i];
string += '<span>' + character + '</span>';
}

$(this).html(string);

firstItemWidth = $(this).find('span:first').width();
lastItemWidth = $(this).find('span:last').width();
alignWidth = containerWidth - (firstItemWidth + lastItemWidth);

$(this).find('span').each(function(i) {
if (0 === parseInt(i)) {
// The first item
$(this).css({position: 'absolute', left: 0, top: 0});
} else if ((parseInt(textArray.length) - 1) === parseInt(i)) {
// The last item
$(this).css({position: 'absolute', right: 0, top: 0});
} else {
// Other items
// stuck in here......
var left = (i * singleWidth) - $(this).width() + firstItemWidth;
$(this).css({position: 'absolute', left: left, top: 0});
}
});

}
});
}

卡在中间项位置的算法上。

最佳答案

我认为这是最简单的解决方案。适用于所有浏览器(包括 IE)

  1. 无需复杂(且不可靠)的宽度检测和计算。
  2. 不指定宽度/高度
  3. 没有相对/绝对定位
  4. 使用纯 HTML/CSS/JS/JQ 技巧。

Working Fiddle

HTML:(非常简单)

<div class="Box">
<div class="Centered">
<div class="Spread">Lighting</div>
<div class="Spread">我是中文</div>
</div>
</div>

CSS:(整洁而棘手)

*
{
margin: 0;
padding: 0;
}
.Box
{
width: 150px;
height: 150px;
border: 1px solid red;
margin: 6px;
}
.Box:before
{
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-left: -5px;
}
.Centered
{
display: inline-block;
vertical-align: middle;
width: 100%;
}
.Spread
{
width: 100%;
text-align: justify;
font-size: 0;
}
.Spread span
{
font-size: medium;
}
.Spread:after
{
content: '';
display: inline-block;
height: 0px;
width: 100%;
}

JS/JQ:

$.fn.SplitText = function () {
return this.each(function () {
return $(this).html('<span>' + $(this).text().split('').join(' ') + '</span>');
});
}

$(function () {
$('.Spread').SplitText();
})

解释:正如wared 在评论中提到的,IE7 不支持伪类的使用。但它们不是解决方案所必需的。这是一个 Fiddle适用于 IE7(当然还有所有其他浏览器)。

垂直对齐是如何工作的?当 vertical-align:middle; 用于 inline 元素时,它会将此元素的中间与其他 inline 元素对齐同一条线。这就是为什么我要用 height:100%; 创建一个 inline 元素,所以当我们将 inline 元素对齐到他的中间时,它会实际上是容器的中间。

水平分布是如何运作的?利用 text-align:justify;,我们创建一个空的 inline 元素 (height:0;) 和 width:100%;,我们可以想象它需要整行,其余的文字放在第二行。使用 justify 使第二行均匀分布以占用与第一行相同的空间。

如果您需要更多解释,请告诉我。

关于javascript - 需要将字符串拆分为字符并与容器对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20539559/

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