87,904
社区成员
发帖
与我相关
我的任务
分享
<script>
function test()
{
var div = document.getElementById("d");
var content = div.innerHTML;
var tmp = document.createElement("div");
tmp.className = div.className;
tmp.style.width = "0";
tmp.style.whiteSpace = "nowrap";
document.body.appendChild(tmp);
var maxLen = div.offsetWidth * 4;
var arr = [];
for (var i = 0; i < content.length; i++)
{
if (tmp.offsetWidth >= maxLen)
{
arr.length = arr.length - 1;
div.innerHTML = arr.join("");
break;
}
arr.push(content.charAt(i));
tmp.innerHTML = arr.join("");
}
document.body.removeChild(tmp);
}
</script>
<style>
.container{
width:100px;
height:100px;
border:1px solid #000;
line-height:30px;
}
</style>
<body>
<div id="d" class="container">
打开警方阿拉斯加打开警方阿拉斯加打开警方阿拉斯加打开警方阿拉斯加打开警方阿拉斯加打开警方阿拉
</div>
<input type="button" onclick="test()" value="点我试试">
</body>