[英]html set title attribute to display line break
如何在简单的 html 元素上使用标题显示悬停事件的换行符? / 要使用的正确代码是什么?
我正在尝试像这样设置标题属性:
.setAttribute('title', 'line1 &#013; \<br />- /n \/n /r line2')
..那行不通。 是不会在任何地方中断。
--- 代码示例 ---
const box = document.querySelector('.box'); // set `id` attribute on element box.setAttribute('title', 'line1 
 <br />- /n \/n /r line2');
<div class="box" style="background-color: pink; width: 20px; height: 20px"> </div> <br><br> this works with "&#013;" <div style="background-color: blue; width: 20px; height: 20px" title="line1 
 <br />- /n \/n /r line2"> </div>
您很接近,但在\n
中使用了斜杠而不是反斜杠。 另一方面,HTML 代码不会被解析,因此<br>
或实体将无法在 JavaScript 中工作。
从HTML 标准:
如果 title 属性的值包含 U+000A LINE FEED (LF) 字符,则内容被拆分为多行。 每个 U+000A LINE FEED (LF) 字符代表一个换行符。
根据JavaScript 转义序列, \n
映射到该字符。
您还可以将 unicode 字符添加到这样的字符串中:
box.setAttribute('title', "line1\u{000A}line2");
另外,您可以使用模板文字代替使用常规字符串作为属性值,它允许您在字符串中添加换行符:
box.setAttribute('title', `line1
line2`);
请注意 HTML 规范中的以下注释。 您不应依赖 title 属性来提供其他方式未提供的信息。
目前不鼓励依赖 title 属性,因为许多用户代理没有按照本规范的要求以可访问的方式公开该属性(例如,需要诸如鼠标之类的指点设备来导致工具提示出现,这不包括仅使用键盘的用户和仅触摸的用户,例如拥有现代手机或平板电脑的任何人)。
// set by means of Unicode document.querySelector('.box1').setAttribute('title', "line1\u{000A}line2"); // set `title` attribute on element by means of template literal document.querySelector('.box2').setAttribute('title', `line1 line2`); // simple with \n document.querySelector('.box3').setAttribute('title', `line1\nline2`);
<p class="box1" style="background-color: blue; width: 20px; height: 20px"></p> <p class="box2" style="background-color: pink; width: 20px; height: 20px"></p> <p class="box3" style="background-color: green; width: 20px; height: 20px"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.