围绕中心字对齐文本

Aligning text around a pivot word

本文关键字:对齐 文本      更新时间:2023-09-26

如何将文本围绕"pivot"字对齐,使该pivot字出现在其行中央(当在浏览器中显示时)?

假设[]标记行的开始和结束,X是中线标记,为了清楚起见,这里包括了。

那么,对于单行:

                                       X
[            I am centered around my PIVOT word.                               ]
[                        Here is the PIVOT word of this second example.        ]

对于多行,可以是这样的:

                                       X
[                                                  This is multiline text with ]
[    one word which functions as the PIVOT.  Then we have some more boring     ]
[ multiline text you don't have to worry about                                 ]

修改了我的第一个答案。现在好多了。看小提琴。它是基于你在中心词上分割段落的想法。关键字和最后一节放在段落的后面。然后将前半部分(在pivot字之前)拆分为一个数组,该数组向后遍历(每次弹出最后一个元素)以填充跨度,直到它达到其宽度。这将不断重复,直到数组中没有剩余的单词为止。我不是一个以英语为母语的人,所以我希望这些都能对你有所帮助。

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <script type="text/javascript" src="js/jquery-1.9.0/jquery.min.js"></script>
        <style type="text/css">
            .container {
                width: 500px;
                border: 1px solid #ddd;
            }
            .pivotWord {
                background-color: red;
                color: white;
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <p>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in PIVOT voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </p>
            <p>
                Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. PIVOT Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </p>
            <p>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et PIVOT dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in  voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </p>
            <p>
                Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.  Excepteur sint occaecat cupidatat non PIVOT proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </p>
        </div>


        <script type="text/javascript">
            function pivotAround(pivotword){
                $('p').each(function(){
                    //initialize a few things
                    var sentence = $(this).html();
                    var splittedSentence = sentence.split(pivotword);
                    var paragraphWidth = $(this).width();
                    $(this).html("");
                    //create elements from the sentence parts.
                    var pivotSpan = $("<span />", {
                        'class': 'pivotWord'
                    }).html(pivotword);
                    var postSpan = $("<span />", {
                    }).html(splittedSentence[1]);
                    //append them to the DOM
                    $(this).append(pivotSpan)
                                 .append(postSpan);
                    //get size of pivotSpan
                    var pivotSpanWidth = pivotSpan.width();
                    //calculate where the pivot word should be
                    var pivotSpanLeftMargin = (paragraphWidth / 2) - (pivotSpanWidth / 2);
                    //make global array of splittedSentence[0]
                    preSpanArray = splittedSentence[0].split(' ');
                    distributeWithinMargin(pivotSpanLeftMargin, this);
                    //array not empty?
                    while(preSpanArray.length > 0){
                        distributeWithinMargin(paragraphWidth, this);
                    }
                });
            }
            function distributeWithinMargin(margin, element) {
                var span = $("<span />", {
                    'style': 'margin-left: -40000px'
                });
                $(element).prepend(span);
                while (preSpanArray.length > 0 && span.width() <= margin) {
                    var lastElement = preSpanArray.pop();
                    span.prepend(lastElement + " ");
                }
                /*
                 * last word makes the span too wide, so push it back to the stack
                 * only do this when array not empty, or you will end up in an
                 * endless loop
                 */ 
                if (preSpanArray.length > 0) {
                    preSpanArray.push(lastElement);
                    //remove that word from the span
                    var firstSpaceIndex = $(span).html().indexOf(" ");
                    $(span).html($(span).html().substring(firstSpaceIndex + 1));
                }
                //calculate the text-indent from that value
                var textIndent = margin - span.width();
                $(span).css('margin-left', textIndent);
            }
            pivotAround("PIVOT");       
        </script>
    </body>
</html>

所以我做了一个fiddle它的没有完全完成它有一些bug ,每次你调整容器的大小,你必须点击RUN按钮,如果有2行以上的pivot它开始打破,但它在基本工作:http://jsfiddle.net/dFv3b/1/

HTML:

<div class="container">
    <p>I am centered around my PIVOT word.</p>
    <p>Here is the PIVOT word of this second example.</p>
    <p>This is multiline text with one word which functions as the PIVOT then we have some more boring multiline text you don't have to worry about.</p>
</div>

JS/jQuery:

var containerWidth = $(".container").width();
$("p:contains('PIVOT')").html(function() {
    var text = $(this).html().split(' ');
    for( var i = 0, len = text.length; i < len; i++ ) {
        var p = ("PIVOT" == text[i]) ? " pivot" : "";
        text[i] = '<span class="word-' + i + p + '">' + text[i] + '</span>';;
    }
    return text.join(' ');
}).each(function() {
    var $pivot   = $(this).find(".pivot");
    var pivotPos   = $pivot.offset().left;
    var pivotWidth = $pivot.width();
    if (pivotPos + pivotWidth / 2 < containerWidth / 2) {
        // one line in the 1nd half
        $(this).css("text-indent", (containerWidth / 2) - (pivotWidth / 2) - pivotPos);
    } else {
        // multi line in the 2nd half
        var indent;    
        // indent half width
        $(this).css("text-indent", containerWidth / 2);
        pivotPos = $pivot.offset().left;
        while (pivotPos + pivotWidth / 2 < containerWidth / 2) {
            var indent = Number($(this).css("text-indent").replace(/[^-'d'.]/g, ''));
            $(this).css("text-indent", indent + 1);
            pivotPos = $pivot.offset().left;
        }
        // return just before half
        $(this).css("text-indent", indent -1);
        pivotPos = $pivot.offset().left;
        var words = $(this).find("span").toArray();
        var begin;
        // find the first word on pivot line       
        for(var i=0, len=words.length; i<len; i++) {
            if (0 === $(words[i]).offset().left) {
                begin = words[i];
                break;
            }
        }
        $(begin).css("margin-left", String((containerWidth /2) - (pivotWidth /2) - pivotPos) + "px");
    }
});

最后,我找到了一种方法来做这个表。如果你有不同的table的宽度,你应该玩的leftright的宽度值(必须是相等的百分比)td -s。

<table width="700px">
<tr>
<td style="width:47%;height:25px;text-align:right;overflow:hidden;whitespace: nowrap;">text</td>
<td style="min-width:40px;width:40px;height:25px;">pivot</td>
<td style="width:47%;height:25px;overflow:hidden;whitespace: nowrap;">text</td>
</tr>
<tr>
<td style="width:47%;height:25px;text-align:right;overflow:hidden;whitespace: nowrap;">longer text tot the left</td>
<td style="min-width:40px;width:40px;height:25px;">pivot</td>
<td style="width:47%;height:25px;overflow:hidden;whitespace: nowrap;">short here</td>
</tr>
<tr>
<td style="width:47%;height:25px;text-align:right;overflow:hidden;whitespace: nowrap;">sample</td>
<td style="min-width:40px;width:40px;height:25px;">pivot</td>
<td style="width:47%;height:25px;overflow:hidden;whitespace: nowrap;">text text text text text text text</td>
</tr>
</table>

我也为你演奏了小提琴!

我可以想到一个纯css的解决方案,但它只有在前后文本不超过一行的情况下才有效。你可以在http://jsfiddle.net/2UQhC/5/上找到它(你需要点击"run"才能正确地看到它)。

基本思想是这样的:

  • 有一个位置:relative
  • 的父容器
  • 一个段落在句首,一个段落在句尾。每个在开始处包含一个跨度,其中包含pivot字。
  • 两个段落都以position:absolute的形式放置。开始有右:50%(所以它的右边缘在中间),结束也有左:50%。
  • 段落中的跨度都向中心浮动。
  • span然后被赋予具有基于百分比的负边距的伪元素,将各自的容器推到中心。基于百分比的宽度使用包含浮动的宽度(而不是行块),这意味着这些百分比宽度的基础将始终是以您选择的任何字体或字体大小布局枢纽字的实际宽度。

下面是代码,以防太深奥,使用'lilacs'作为中心词:

<div>    
    <p id="left"><span>LILACS</span>April is the cruellest month, breeding&nbsp;</p>
    <p id="right"><span>LILACS</span>&nbsp;out of the dead land</p>
</div>

和CSS -

div {
    position: relative;
}
#left {
    position: absolute;
    right: 50%;
}
#right {
    position: absolute;
    left: 50%;
}
#left span {
    float: right;
}
#right span {
    float: left;
    visibility: hidden;
}
#left span:after {
    content: "";
    margin-right: -50%;
}
#right span:before {
    content: "";
    margin-left: -50%;
}

无论句子两边的宽度如何(只要不是多行),它都可以工作,并且应该在IE8 plus中工作。