如何将一段文字放在HTML,CSS或JavaScript中的特定单词的中心? [英] How to center a paragraph of text on a particular word in HTML, CSS, or JavaScript?

查看:87
本文介绍了如何将一段文字放在HTML,CSS或JavaScript中的特定单词的中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上居中一段,像这样:

I have a passage that is centered on the page, like this:

 _________________________
|                         |
| Once upon a time, there |
|   lived a squirrel who  |
|  lived in the middle of |
|       the forest.       |
|_________________________|

我需要调整居中位置,以使特定标记的单词在页面上水平居中.在此示例中,单词"who"居中:

I need to adjust the centering such that a specifically marked word is horizontally centered on the page. In this example, the word "who" is centered:

 _________________________
|                         |
|        Once upon        |
|  a time, there lived a  |
|  squirrel who lived in  |
|    the middle of the    |
|         forest.         |
|_________________________|

  • 在HTML中用<div>标记(即<center>Once upon a time, there lived a squirrel <div style="centered">who</div> lived in the middle of the forest.</center>)标记的单词.
  • HTML出现在我对编辑HTML本身几乎没有控制权的应用程序中(文本已经用CSS样式标签进行了标记),但是可以修改样式表或将代码(例如JavaScript)添加到标题中以进行修改该样式的呈现方式.
    • The word who is marked in the HTML with a <div> tag, i.e. <center>Once upon a time, there lived a squirrel <div style="centered">who</div> lived in the middle of the forest.</center>.
    • The HTML appears in an application in which I have little control over editing the HTML itself (the text is already marked with CSS style tags), but can modify the style sheet or add code, such as JavaScript to the header to modify how that style is rendered.
    • 如何将段落集中在HTML,CSS或JavaScript中的特定单词上?

      How can I center a passage on a particular word in HTML, CSS, or JavaScript?

      推荐答案

      将特定目标单词移至单词允许的最佳水平中心

      您可以使用非常简单的JavaScript实现粗略的居中.它所做的只是沿标记扫描,将找到的第一个TextNode转换为用<span>包裹的单词",然后反复尝试插入行换行符直到出现错误,直到找到将目标单词最接近的单词为止.中心.

      shift a particular target word to the best horizontal center that words will allow

      You can achieve a rough centering using quite simple JavaScript. All it does is scan along the mark-up, converts the first TextNode it finds to "words" wrapped with <span>s, and then trials and errors inserting line breaks until it finds the one that will get the target word nearest to the center.

      在小提琴中,我用红色突出显示了代码认为应该休息一下的跨度,并用绿色突出了目标单词.在大多数情况下,它的效果都很好,在少数情况下,您可能会在一行上出现单个单词—但是,可以通过将代码调整为确切的用例来解决此问题.

      In the fiddle I have highlighted in red the spans that the code deems should have a break after, and green for the target word. In the most cases it does quite well, there are a few occurrences where you may end up with a single word on a line — however, this could be fixed by tweaking the code to your exact use-case.

      只是在人们不知道的情况下,这只是可以实现的示例,绝不是完美的—从来没有代码,因为它总是可以改进的,应该改进.

      Just in case people aren't aware, this is an illustration of what can be achieved and is by no means perfect — no code ever is, because it can always be improved, and should be.

      小提琴

      http://jsfiddle.net/s8XgJ/2/

      更新的小提琴,显示带有随机目标词的行为:

      updated fiddle that shows behaviour with a random targeted word:

      http://jsfiddle.net/s8XgJ/3/

      <center>
        Once upon a time, there was a squirrel who lived in the 
        <span class="centered">middle</span> of the forest. I 
        say middle, but without knowing where the edges were, 
        the squirrel had no idea where the center was.
      </center>
      

      我大致上保留了您的标记,但是,正如其他人所说的那样,您应该避免使用中心标记.我也将内部div转换为跨度以保留行内间距.如果您无法做到这一点,您仍然可以使用div,您只需覆盖它的常规显示为display: inline-block;

      JavaScript/jQuery

      jQuery.fn.findYourCenter = function( target ){
        base = $(this); target = base.children(target);
        base.contents().eq(0).each(function(){
          var i = -1, word, words, found, dif,
            last = Infinity,
            node = $(this), 
            text = node.text().split(/\s+/),
            cwidth = Math.round(target.width() * 0.5),
            bwidth = Math.round(base.width() * 0.5),
            breaks = 2 // code will try to insert 2 line breaks
          ;
          node.replaceWith(
            '<span class="word">'+text.join(' </span><span class="word">')+' </span>'
          );
          words = base.find('.word');
          do {
            while ( ++i < words.length ){
              word && word.removeClass('clear');
              word = words.eq(i).addClass('clear');
              dif = Math.round(Math.abs((target.position().left + cwidth) - bwidth));
              if ( dif < last ) { last = dif; found = i; }
            }
            word.removeClass('clear');
            if ( found ) {
              words.eq(found).addClass('clear');
              i = found; found = word = null;
            }
            else {
              break;
            }
          } while ( i < words.length && --breaks );
        });
      };
      

      为了简洁起见,我使用了jQuery.

      CSS

      您将需要以下CSS项:

      CSS

      You'll require this CSS item:

      .clear:after {
        content: '';
        display: block;
        clear: both;
      }
      

      ,如果您的.centered项目是<div>,则可能是以下内容:

      and perhaps the following if your .centered item is a <div>:

      .centered {
        display: inline-block;
      }
      

      然后您需要执行的所有操作是:

      Then all you need execute is:

      jQuery(function($){
        $('center').findYourCenter('.centered');
      });
      


      要使事情变得精确,您必须补偿一些问题-mdash;由于存在这样一个事实,即取决于单词的长度(和位置),您无法始终同时获得段落,行和目标单词的完美中心.上面的代码仍然使行居中,但代价是目标单词被偏移了.如果您希望以该行为中心将单词居中,则可以对上述内容进行改进,以对保留目标跨度的行进行边距修改.

      To get things precise you'll have to offset something — due to the fact that depending on the length (and placement of) words you cannot always achieve perfect center for paragraph, line and target word all at the same time. The above code still keeps the line centered, at the cost of the target word being offset. You could improve the above to make margin modifications to the line that holds the target span, if you wanted to center the word at the cost of the line.

      当前,如果目标单词出现在第一个说出的五个单词中,则居中不太可能实现,主要是因为此方法依赖于自动换行和换行符.如果由于段落开头出现单词而无法使用任何内容,则无法执行任何操作—.除了用于引入边距,填充或文本缩进之外.

      Currently, if the target word appears in the first say five words, centering is unlikely to be achieved, basically because this method relies on word-wrap and line-breaks. If neither can be used due to the word being at the beginning of the paragraph, then nothing can be done — save for introducing margin, padding or text-indent.

      此代码依赖于能够正确读取<span>元素的位置.较旧的浏览器,例如IE6和Safari/Opera的早期版本对此存在问题.

      This code relies on being able to read the position of <span> elements correctly. Older browsers e.g. IE6 and early versions of Safari/Opera have had problems with this.

      还有另一件事要注意.此代码依赖于浏览器在同一同步执行循环中立即重新计算其内部度量.大多数现代浏览器似乎都可以做到这一点—在大多数情况下—但是,您可能会发现需要实现setTimeout(func, 0)setImmediate延迟才能在较早的系统上运行.

      One further thing to note. This code relies on the browser recalculating it's internal measurements immediately in the same synchronous execution loop. Most modern browsers seem to do this — in most cases — however you may find you need to implement setTimeout(func, 0) or setImmediate delays in order for this to work on older systems.


      这是一个相当疯狂的请求,它的目的是什么? :)

      This is a rather bonkers request, what exactly is it for? :)

      这篇关于如何将一段文字放在HTML,CSS或JavaScript中的特定单词的中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆