如何使用JS测试字符/ HTML实体是否符合换行符或不中断?
换行符的例子:
ServerB
<这是一个空间
非破坏字符的示例是:
-
<不间断的空间
<不间断的连字符‑
<字木匠我知道还有更多的HTML实体是行/非中断字符,我不知道它们是什么。如何在不事先知道的情况下检查是否有换行符?
答案 0 :(得分:1)
您可以通过创建具有最小宽度的测试div来测试它,然后检查文本是否包装到下一行。
var tester=document.getElementById("test");
var html=document.getElementById("html").value;
function testfor() {
var tester=document.getElementById("test");
var html=document.getElementById("html").value;
var itIs=false;
tester.innerHTML="a";
var height_init=tester.clientHeight;
console.log(height_init);
tester.innerHTML+=html+"a";
var height_final=tester.clientHeight;
console.log(height_final);
if(height_final > height_init) {
itIs=true
}
document.getElementById("return").innerHTML=itIs;
}
document.getElementById("html").addEventListener("keydown", function(e) {
if (!e) { var e = window.event; }
// Enter is pressed
if (e.keyCode == 13) { testfor(); }
}, false);

#test{
width: 1px;
line-height: 30px;
font-size: 18px;
}

<div id="test">this text box will take any length of string, and test if the lines break, however it was not designed to handle more than one character/entity/tag at a time</div>
<input id="html" type="text" placeholder="type an HTML character/entity/tag"/>
<p id="return">
</p>
&#13;