簡體   English   中英

html設置title屬性顯示換行符

[英]html set title attribute to display line break

如何在簡單的 html 元素上使用標題顯示懸停事件的換行符 / 要使用的正確代碼是什么?

我正在嘗試像這樣設置標題屬性:

.setAttribute('title', 'line1 &amp;#013; \<br />-  /n \/n /r line2')

..那行不通。 是不會在任何地方中斷。

在此處輸入圖像描述

..................... 在此處輸入圖像描述

--- 代碼示例 ---

 const box = document.querySelector('.box'); // set `id` attribute on element box.setAttribute('title', 'line1 &#013; <br />- /n \/n /r line2');
 <div class="box" style="background-color: pink; width: 20px; height: 20px"> </div> <br><br> this works with "&amp;#013;" <div style="background-color: blue; width: 20px; height: 20px" title="line1 &#013; <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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM