How to add a tooltip to a div

I have a div tag as follows:

<html>
    <head></head>
    <body>
        <div>
            <label>Name</label>
            <input type="text"/>
        </div>
    </body>
</html>

Now I want a simple javascript for displaying a tooltip on :hover the div. Can someone please help me out? The tooltip should also have a fade in/out effect.


For the basic tooltip, you want:

<div title="This is my tooltip">

For a fancier javascript version, you can look into:

http://www.designer-daily.com/jquery-prototype-mootool-tooltips-12632

The above link gives you 12 options for tooltips.


It can be done with CSS only , no javascript at all : running demo

  • Apply a custom HTML attribute, eg. tooltip="bla bla" to your object (div or whatever):

    <div tooltip="bla bla">
        something here
    </div>
    
  • Define the :before pseudoelement of each [tooltip] object to be transparent, absolutely positioned and with tooltip="" value as content:

    [tooltip]:before {            
        position : absolute;
         content : attr(tooltip);
         opacity : 0;
    }
    
  • Define :hover:before hovering state of each [tooltip] to make it visible:

    [tooltip]:hover:before {        
        opacity : 1;
    }
    
  • Apply your styles (color, size, position etc) to the tooltip object; end of story.

  • In the demo I've defined another rule to specify if the tooltip must disappear when hovering over it but outside of the parent, with another custom attribute, tooltip-persistent , and a simple rule:

    [tooltip]:not([tooltip-persistent]):before {
        pointer-events: none;
    }
    

    Note 1: The browser coverage for this is very wide, but consider using a javascript fallback (if needed) for old IE.

    Note 2: an enhancement may be adding a bit of javascript to calculate the mouse position and add it to the pseudo elements, by changing a class applied to it.


    You don't need JavaScript for this at all; just set the title attribute:

    <html><head></head>
    <body>
    <div title="Hello, World!">
    <label>Name</label>
    <input type="text"/>
    </div>
    </body>
    </html>
    

    Note that the visual presentation of the tooltip is browser/OS dependent, so it might fade in and it might not. However, this is the semantic way to do tooltips, and it will work correctly with accessibility software like screen readers.

    See this jsfiddle.

    链接地址: http://www.djcxy.com/p/81352.html

    上一篇: 在样式设置器中设置CornerRadius的特定成员时出现问题

    下一篇: 如何将工具提示添加到div