如何“限制”<p>内的文本?

问题描述 投票:0回答:4

我这里有一个邮件模板通讯: http://www.newsletter.vendopor.com/m29-04-13/index2.html

但最后有一个包含该文本的段落: 感谢您的支持,我们羡慕您的朋友...

这个文本,走出段落(我在css中有一个宽度380的属性,并且一直走出去)。

在本页末尾

我用Google搜索过,但找不到解决方案

在 Chrome 上运行良好,但在 Mozilla(最新版本)中文本会消失。

html text out
4个回答
13
投票

您可以使用
text-overflow: ellipsis;

div {
    width:200px; 
    overflow:hidden; 
    border:1px solid #f00;
    text-overflow:ellipsis;
    white-space:nowrap; 
}
<div>This is very very long text This is very very long text This is very very long text </div>


7
投票
<?php echo substr('your text',0,500); ?>

打印文本的前 500 个字符

或者当您不想使用 php,只想在到达块末尾时文本消失,请在 div 块的 css 中添加

overflow:hidden;


0
投票

我可能已经为你制定了一个很好的解决方案!我不太确定您想要什么样的“限制”,并且您最初发布的时事通讯链接现已失效,但我会尽力而为!

许多公认的解决方案似乎都使用带有

text-overflow
属性的 CSS 以及使用字符单位 (
width
) 的
ch
。 这是一个很好的解决方案,但我看到其他人想要一个 JavaScript 答案来直接编程控制。 也许您会发现我的解决方案比一堆 CSS 属性和规则更容易使用! Anywho,只是为了让您知道,我的解决方案源于 Josh 在这篇文章中的回答: 如何限制段落中文本的长度。 我认为 Josh 的想法是使用 JS,并决定更进一步。

如果我们考虑这里的问题,通常的想法是限制每个“行”上的字符数 段落的文本字符串。这基本上可以防止您的文本溢出或超出范围。 但正如我们所知,段落文本字符串本身只是一长行文本,因此我们必须定义什么是“行” 是为了问题的解决。有什么比使用“换行”字符更好的方式来定义“行”呢! (好吧,这有点俗气)。 但你明白了。我们将使用换行符或 ' 停止段落文本中每行的字符数 '.

对于实现,我认为迭代编码会很难看,我只是“感觉”递归路线。 如果您不熟悉递归,我所做的就是让函数或方法调用自身并粉碎 调用堆栈,直到它达到我定义的基本情况,就可以说我们已经解决了它!

这是版本 1,如果当前子字符串长于我们的最大字符限制,它只是附加一个换行符 长度;否则,它只会到达末尾并最终达到长度,或超过最后一个有效字符索引的长度。

/*=======================*/
/*Made by: Brendan Sting */
/*=======================*/

/* ---Limit text inside a <p> tag with vanilla JavaScript, version 1; bad wrapping/cutoff--- */

function truncateText(selector, maxLength, startAt) {
    var element = document.querySelector(selector);
    var truncated = element.innerText;
    
    // BASE CASE:
    if (startAt >= truncated.length)
    {
        return "";
    }
        
    // If the currently looked at substring is longer than the limit, cut it:
    if (truncated.substring(startAt).length > maxLength) {
        truncated = truncated.substring(startAt, (startAt+maxLength)) + '\n';
    }
    
    // Else, just write it out with no newline needed:
    else
    {
        truncated = truncated.substring(startAt);
    }
    
    // Recursive return:
    return truncated + truncateText(selector, maxLength, (startAt + maxLength));
}

document.querySelector('p').innerText = truncateText('p', 30, 0);
/* --- END OF CODE SNIPPET V1 ---  */
<!-- TEST COVERAGE -->

<!--Test case 1: PASS -->
<p>Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined.</p>

<!-- Test case 2: PASS -->
<!--<p>&emsp;Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined.</p> -->

<!-- Test case 3: PASS -->
<!--<p>&emsp;Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined.<br><br>&emsp;Now, what if I started typing down here, huh? Can you handle this text as well?</p> -->

<!--Test case 4: PASS -->
<!--<p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.</p>-->

<!-- Test case 5: PASS -->
<!--<p></p>-->

<!-- Test case 6: PASS -->
<!--<p>12345678910         111213141516170000000000000000000000   1819202122</p> -->

<!-- END OF TESTS -->

这是……嗯,它严格执行我们告诉它的操作。它只是截断超出我们在查询调用中定义的限制的字符。 但还可以改进!我不了解你,但我讨厌我的话语被分成不同的部分。 相反,更好的解决方案应该像 Microsoft Word 那样,如果该行将每个单词移动到换行符 超出页面上设置的字符限制。这使单词保持在一起并使我们的行数保持在我们想要的限制!

好吧,拿两个!让我们扩展我们的问题,如果该行的最后一个单词被截断超过限制,那么它的整个单词应该是 移至下一行以进行完整打印。

乍一看,这似乎很简单,但我的原始版本 1 JS 代码的其他 7 个版本却不然。我们不仅需要完成 在尊重字符限制的同时保留单词,但我们还需要考虑边缘情况,例如本身很长的单词 超过限制。为了在尊重每行字符限制的同时保留单词,我们可以搜索找到的最近的空格 在段落字符串的前面并将我们的结束索引(我们将在其中附加换行符)移动到该空白处,这本质上是 将单词放在换行符后面!如果没有可用的空格,那么,我们将继续正常地剪切单词,例如 在版本 1 中;但这绝对不应该发生,因为段落中必然有空格!此外,我们实际上可以利用这个原理 通过使用一些辅助函数的返回来处理我之前提到的使用非常长的单词的边缘情况示例。

哇,好吧,太多了!但我只是想确保您了解我所做的解决方案的设计。 现在,让我们看看最终的实现:

/*=======================*/
/*Made by: Brendan Sting */
/*=======================*/

/* --- Limit text inside a <p> tag with vanilla JavaScript; version 8 --- */

/* === LATEST WORKING VERSION === */

// Tries to find the last available blank space to resort to:
function findLastBlankSpaceStartingFrom(inString, startIndex)
{
    for (let loopIndex = startIndex; loopIndex > -1; loopIndex--)
  {
    if (inString[loopIndex] == " ")
    {
        return loopIndex;
    }
  }
  
  return -1; // Darn, we couldn't find it; handle it
}

// Frees any chars that have been disconnected from the current substring line by past newline characters (also from <br> tags)
function freeUpAnyNewlineSeparatedCharSpace(inString, upUntilThisPoint, startingFromHere) //upUntilThisPoint = startAt index, startingFromHere = lastCharIndex
{
    var extraAvailableChars = 0;
  let startCountingSwitchEnabled = false;

    if (startingFromHere > upUntilThisPoint)
  {
    for (let loopIndex = startingFromHere; loopIndex >= upUntilThisPoint; loopIndex--)
    {
      if (inString[loopIndex] == '\n')
      {
        startCountingSwitchEnabled = true;
      }

      if (startCountingSwitchEnabled)
      {
        extraAvailableChars++;
      }
    }
  }
  else
  {
    for (let loopIndex = startingFromHere; loopIndex <= upUntilThisPoint; loopIndex++)
    {
      if (inString[loopIndex] == '\n')
      {
        startCountingSwitchEnabled = true;
      }

      if (startCountingSwitchEnabled)
      {
        extraAvailableChars++;
      }
    }
  }
  
  return extraAvailableChars;
}

function getNewEndpointBeforeLineOverflow(ofThisString, atLastCharIndex, startOfLine)
{
    var finalCharIndex = atLastCharIndex;

  // If last char index on the line is below the last char of the entire string, then:
  if (atLastCharIndex < (ofThisString.length - 1))
  {
    // If there's a non-blank, non-space character past the last char to limit to, then:
    if ((ofThisString[atLastCharIndex] != ' ') && (ofThisString[atLastCharIndex + 1] != ' '))
    {
        // Try and find a previous blank space to resort to and end on:
        var prevBlankIndex = findLastBlankSpaceStartingFrom(ofThisString, (atLastCharIndex)); 

        if ((prevBlankIndex != -1) && (prevBlankIndex >= startOfLine)) // Did we find a valid blank space within this portion of the line?
      {
        finalCharIndex = prevBlankIndex; //Index of the blank space now
      }
    }
  }
  else 
  {
    // If the initial overflow index point, the last char point, is past or at the string's final valid char index,
    // then we have no choice but to reposition it at the text's final char index:
    finalCharIndex = (ofThisString.length - 1);
  }
  
  return finalCharIndex; 
  
}


function truncateText(selector, maxLength, startAt) {
    var element = document.querySelector(selector);
    var truncated = element.innerText;
    let lastCharIndex = (startAt + maxLength) - 1;
    
    // BASE CASE:
    if (startAt >= truncated.length)
    {
        return "";
    }
        // If the currently looked at substring is longer than the limit, cut it:
    if (truncated.substring(startAt).length > maxLength) 
    {
        lastCharIndex = getNewEndpointBeforeLineOverflow(truncated, lastCharIndex, startAt);
            
        var extraLineSpace = freeUpAnyNewlineSeparatedCharSpace(truncated, startAt, lastCharIndex);
        if (extraLineSpace > 0)
        {
            lastCharIndex = lastCharIndex + extraLineSpace;
          lastCharIndex = getNewEndpointBeforeLineOverflow(truncated, lastCharIndex, startAt)
        }
        
        truncated = truncated.substring(startAt, (lastCharIndex+1)); //Stop at either maxLength or blankSpace+1
        
        // Allow the front-end programmer to input tabs or spaces at the front with &emsp; or &nbsp; (etc.), but if it's a raw space then cut it out:
        // (This conditional structure has been reduced thanks to the power of .innerText)
        if (truncated[startAt] == ' ')
        {
            truncated = truncated.trim() + '\n';
        }
        else
        {
            truncated = truncated.trimEnd() + '\n';
        }
     
    }
    
    // Else, just write it out with no newline needed:
    else
    {
        truncated = truncated.substring(startAt);
    }
    
    // Recursive return:
    return truncated + truncateText(selector, maxLength, (lastCharIndex+1) );
    
}

document.querySelector('p').innerText = truncateText('p', 30, 0);
/* --- END OF CODE SNIPPET V8 ---  */
<!-- TEST COVERAGE -->

<!--Test case 1: PASS -->
<p>Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined.</p>

<!-- Test case 2: PASS -->
<!--<p>&emsp;Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined.</p> -->

<!-- Test case 3: PASS -->
<!--<p>&emsp;Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined.<br><br>&emsp;Now, what if I started typing down here, huh? Can you handle this text as well?</p> -->

<!--Test case 4: PASS -->
<!--<p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.</p>-->

<!-- Test case 5: PASS -->
<!--<p></p>-->

<!-- Test case 6: PASS -->
<!--<p>12345678910         111213141516170000000000000000000000   1819202122</p> -->

<!-- END OF TESTS -->

希望我的代码和解决方案能够以某种方式帮助您,如果至少能让您了解如何使用 JavaScript 解决它。


-3
投票

我找到了,这添加到了段落中: 空白:正常; 您可以在这里了解一些有关空白的信息:sidar.org/recur/desdi/traduc/es/css/... 现在在 mozilla 中运行良好,非常感谢大家!

© www.soinside.com 2019 - 2024. All rights reserved.