文字溢出實現溢出的部分再放入一個新產生的div中具體代碼

來源:互聯網
上載者:User

看到群裡有人提了一個問題,說文字溢出,如何?溢出的文字放入一個新產生的div中,

想了一下原理,就是判斷是否能在div裡放下,如果不能,則在應該斷開的地方,差入到新的div中,代碼如下:
複製代碼 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312" />
<title>文字自動分插不同的div-Jason Yu</title>
<style type="text/css">
*{margin:0;padding:0;}
body{line-height:24px;font-family:SimSun;font-size:12px;color:#000;}
#box1{height:96px;}
.box{width:200px;overflow:hidden;margin-top:10px;border:1px solid #000;}
</style>
</head>
<body>
<div id="box1" class="box"></div>
<script type="text/javascript">
var str = "這裡是一段話,這短話的文字可以很隨意的哦,只要達到一定數量,就自動會分頁,你信不信?不信也得信啊,這是真的,哪怕再長的文字,我複製一段話吧,下面這一段話就是複製過來的,我要準備複製了哦,準備好了沒呢?這裡是一段話,這短話的文字可以很隨意的哦,只要達到一定數量,就自動會分頁,你信不信?不信也得信啊,這是真的,哪怕再長的文字,我複製一段話吧,下面這一段話就是複製過來的,我要準備複製了哦,準備好了沒呢?";
var oBox1 = document.getElementById("box1");
function fnTextOver(n1){
var newBox2 = document.createElement("div");
document.body.appendChild(newBox2);
newBox2.className = "box";
for(var i=n1; i<=str.length; i++){
newBox2.innerHTML = str.substring(n1,i);
if(newBox2.offsetHeight<=98){
if(i==str.length){
newBox2.style.height = "96px";
}
}else{
newBox2.innerHTML = str.substring(n1,i-1);
newBox2.style.height = "96px";
arguments.callee(i-1);
break;
}
}
}

function fnShowText(){
var newBox = document.createElement("div");
document.body.appendChild(newBox);
newBox.className = "box";
for(var i=1; i<=str.length; i++){
newBox.innerHTML = str.substring(0,i);
if(newBox.offsetHeight<=98){
oBox1.innerHTML = str.substring(0,i);
if(i==str.length){
document.body.removeChild(newBox);
}
}else{
document.body.removeChild(newBox);
fnTextOver(i-1);
break;
}
}
}
fnShowText();
</script>
</body>
</html>

補充一下,可能出現的問題1、符號在下一個div第一個出現2、字母如"student"會被斷開寫,及其他問題,需用正則判斷一下。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.