简体   繁体   中英

html set title attribute to display line break

How can I display line-breaks for a hover event using title on a simple html-element? / What is the proper code to be used?

I am trying to set the title attribute like so:

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

..That does not work. Is does not break anywhere.

在此处输入图像描述

.................... 在此处输入图像描述

--- Code sample ---

 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>

You were close, but used a slash instead of a backslash in \n . HTML code, on the other hand, will not get parsed, so <br> or entities will not work from JavaScript.

From the HTML Standard :

If the title attribute's value contains U+000A LINE FEED (LF) characters, the content is split into multiple lines. Each U+000A LINE FEED (LF) character represents a line break.

As per JavaScript Escape sequences , \n maps to that character.

You also can add unicode characters to a string like this:

box.setAttribute('title', "line1\u{000A}line2");

Plus, instead of using a regular string as the attribute value, you can use a template literal , which allow you to add line breaks to the string:

box.setAttribute('title', `line1
line2`);

Please beware the following remark from the HTML specification. You should not rely on the title attribute to provide information that is not provided by other means.

Relying on the title attribute is currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (eg, requiring a pointing device such as a mouse to cause a tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or tablet).

 // 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM