3

如何围绕“枢轴”词对齐文本,以使枢轴词出现在其行的中心(在浏览器中显示时)?

说出[]标记行的开头和结尾,并且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                                 ]
4

4 回答 4

1

修改了我的第一个答案。现在效果好多了。见小提琴。它基于您在枢纽词上拆分段落的想法。枢轴词和最后一节被放回段落中。前半部分(在枢轴词之前)然后被拆分为一个数组,该数组向后遍历(每次弹出最后一个元素)以填充跨度,直到达到其宽度。这将不断重复,直到数组中没有更多的单词。我不是以英语为母语的人,所以我希望这一切都有意义。

<!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>
于 2013-05-15T19:38:27.203 回答
1

所以我做了一个小提琴,它还没有完全完成它有一些错误,每次调整容器大小时,你都必须点击RUN按钮,如果在枢轴上方有 2 行它开始中断,但它在基础上起作用: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");
    }
});
于 2013-05-16T00:01:48.027 回答
0

最后我找到了一种用表格来做到这一点的方法。如果你有不同的宽度,你应该使用和-stable的宽度值(必须等于百分比) 。leftright td

<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>

我还为你做了一个小提琴

于 2013-05-15T18:23:40.077 回答
0

我可以想到一个纯 CSS 的解决方案,但它只有在前面和后面的文本不超过一行时才有效。您可以在http://jsfiddle.net/2UQhC/5/找到它(您需要点击“运行”才能正确查看)。

基本思想是这样的:

  • 有一个父容器 position: relative
  • 句首有一个段落,句末有一个段落。每个都在开头包含一个包含枢轴词的跨度。
  • 两个段落都用 position:absolute 放置。开始有 right: 50% (所以它的右边缘在中间)和结束有 left:50% 同样。
  • paras 中的跨度都向中心浮动。
  • 然后为跨度提供基于百分比的负边距的伪元素,将它们各自的容器推到中心。基于百分比的宽度使用包含浮动(而不是行块)的宽度,这意味着这些百分比宽度的基础将始终是以您选择的任何字体或字体大小布置枢轴字的实际宽度。

这是代码,以防太深奥,使用“紫丁香”作为枢纽词:

HTML -

<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。

于 2013-05-15T19:42:37.750 回答