是否可以显示<a> tag text in multiple lines

时间:2016-05-19 09:12:58

标签: javascript html css html5 css3

I have one tag where the text in to that tag will come dynamically from database. Now can it possible to display the tag text in multiple lines? Ex: I want to display only 10 characters per line. If the dynamic text contain 29 characters then it should display in three lines, If the dynamic text contain only 9 characters then it should display in a single line.

Ex:

<a href="http://www.w3schools.com">Welcome to w3schools site</a>

For the above code I need output like,

Welcome to
 w3schools
 site

Any suggestions to display output as shown above?

6 个答案:

答案 0 :(得分:2)

试试这个

var str = "aaaaaaaaaaaaaaaaaaaaaaaaa" ;
var htmlfoo = str.match(/.{1,10}/g).join("<br/>");

$('div').html(htmlfoo);

js fiddle

OR

link

答案 1 :(得分:1)

您可以使用split从字符串中创建数组,并forEach()在每第10个元素后插入<br>

&#13;
&#13;
var a = document.querySelector('a');
var str = a.innerHTML.split('');
str.forEach((e, i) => {
  if(i % 11 == 0 && i != 0) str.splice(i, 0, "<br>");
})

a.innerHTML = str.join('');
&#13;
<a href="http://www.w3schools.com">Welcome to w3schools site</a>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以使用ch

中的宽度值来近似此值

一个'ch`近似于0字符字形的宽度,因此文本空间与字体大小成正比。

* {
  margin: 0;
  padding: 0;
}
.ch10 {
  display: block;
  width: 10ch;
  word-break: break-all;
  margin: 1em;
}
<a class="ch10" href="http://www.w3schools.com">Welcome to w3schools site</a>

<h1><a class="ch10" href="http://www.w3schools.com">0123456789</a></h1>


<a class="ch10" href="http://www.w3schools.com">012345678910</a>

答案 3 :(得分:1)

使用split()获取文字内容中的每个字词。然后检查小于10的单词的长度是否将其插入a,如果单词的长度大于10,请将<br/>插入a

&#13;
&#13;
var aElement = document.querySelector('a');
var words = aElement.innerHTML.split(" ");

var newText = "";
for(var i = 0; i < words.length; i++){
    var textLength = newText.length + words[i].length;
    if (textLength > 10)
        newText += "<br/>";
    
    newText += " " + words[i];
}

aElement.innerHTML = newText;
&#13;
<a href="#">Welcome to w3schools site</a>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

这不是很漂亮,但这就是我做到的:

<强> HTML

<a id="test" href="#">some text that is quite long</a>

<强>的JavaScript

$(document).ready(function(){
  var longtext = $('a#test').text();
  var chars = longtext.split("");
  var newtext = "";
  var charcount = 0;
  if (chars.length > 9)
  {


    for(var i = 0; i < chars.length; i++)
    {

         if (charcount > 9)
         {
              newtext += " <br> ";
              charcount = 0;
         }
         newtext += chars[i];
         ++charcount;
    }
    $('a#test').html(newtext);
  }
});

<强>的jsfiddle

https://jsfiddle.net/ng6ey9zL/

答案 5 :(得分:-1)

首先计算字符数,然后在10个字符的末尾添加<br />标记。