Búsqueda de sitios web

javascript - Agregar una información sobre herramientas a un div


Tengo una etiqueta div así:

<div>
  <label>Name</label>
  <input type="text"/>
</div>

Cómo puedo mostrar una herramienta emergente (tooltip) al :hover del div, preferiblemente con un efecto de aparición/desaparición gradual.

Respuesta #1

Para el tooltip básico, quieres:

<div title="This is my tooltip">

como :

.visible {
  height: 3em;
  width: 10em;
  background: yellow;
}
<div title="This is my tooltip" class="visible"></div>

Para una versión de JavaScript más elegante, puedes mirar:

https://jqueryhouse.com/best-jquery-tooltip-plugins/

El enlace de arriba te ofrece 25 opciones para descripciones emergentes.

Respuesta #2

Se puede hacer solo con CSS, sin javascript en absoluto

ejecutando demo

[data-tooltip]::before {
    /* needed - do not touch */
    content: attr(data-tooltip);
    position: absolute;
    opacity: 0;

    /* customizable */
    transition: all 0.15s ease;
    padding: 10px;
    color: #333;
    border-radius: 10px;
    box-shadow: 2px 2px 1px silver;
}

[data-tooltip]:hover::before {
    /* needed - do not touch */
    opacity: 1;

    /* customizable */
    background: yellow;
    margin-top: -50px;
    margin-left: 20px;
}

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

/* FOR TEST PURPOSES ONLY */
div {
    border: 1px solid silver;
    background: #ddd;
    margin: 20px;
    padding: 10px;
}
<div>Standard div, no tooltip here</div>


<div data-tooltip="Hi, I'm a tooltip. Pretty easy uh ? ;)">Div with standard tooltip. Hover me to see the tooltip.
    <br/>Hovering the tooltip doesn't matter:
    <br/>if you hover out of my boundaries, the tooltip will disappear.</div>


<div data-tooltip="Hi, I'm a persistent tooltip. I won't disappear when hovering me even if out of my parent boundaries. I'll also prevent other tooltips to fire :)" data-tooltip-persistent="foo">Div with persistent tooltip. Hover me to see the tooltip.
    <br/>The tooltip won't expire until you hover on me OR it.</div>
  1. Aplica un atributo HTML personalizado, por ejemplo, data-tooltip="bla bla" a tu objeto (div o lo que sea):

    <div data-tooltip="bla bla">
        something here
    </div>
    
  2. Define el pseudoelemento ::before de cada objeto [data-tooltip] para que sea transparente, posicionado absolutamente y con el valor data-tooltip="" como contenido:

    [data-tooltip]::before {
        position : absolute;
        content : attr(data-tooltip);
        opacity : 0;
    }
    
  3. Define el estado de desplazamiento :hover::before de cada [data-tooltip] para hacerlo visible:

    [data-tooltip]:hover::before {
        opacity : 1;
    }
    
  4. Aplica tus estilos (color, tamaño, posición, etc.) al objeto tooltip; fin de la historia. En la demostración he definido otra regla para especificar si el tooltip debe desaparecer al pasar el ratón sobre él pero fuera del elemento padre, con otro atributo personalizado, data-tooltip-persistent, y una regla sencilla:

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

Nota 1: La compatibilidad del navegador con esto es muy amplia, pero considere usar un recurso de reserva en javascript (si es necesario) para versiones antiguas de IE.

Nota 2: una mejora podría ser agregar un poco de JavaScript para calcular la posición del ratón y agregarla a los pseudoelementos, cambiando una clase aplicada a ello.

Respuesta #3

No necesitas JavaScript para esto en absoluto; solo establece el atributo title:

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

Tenga en cuenta que la presentación visual del tooltip depende del navegador/SO, por lo que puede desvanecerse o no. Sin embargo, esta es la forma semántica de hacer tooltips, y funcionará correctamente con software de accesibilidad como los lectores de pantalla.

Demostración en Stack Snippets

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

Respuesta #4

Aquí hay una implementación pura de CSS 3 (con JS opcional)

Lo único que tienes que hacer es establecer un atributo en cualquier div llamado "data-tooltip" y ese texto se mostrará junto a él cuando pases el cursor sobre él.

He incluido un JavaScript opcional que hará que la información sobre herramientas se muestre cerca del cursor. Si no necesitas esta función, puedes ignorar con seguridad la parte de JavaScript de este fiddle.

Si no quieres la aparición gradual en el estado al pasar el cursor, simplemente elimina las propiedades de transición.

Está diseñado como la descripción emergente de la propiedad title. Aquí está el JSFiddle: http://jsfiddle.net/toe0hcyn/1/

Ejemplo de HTML:

<div data-tooltip="your tooltip message"></div>

CSS :

*[data-tooltip] {
    position: relative;
}

*[data-tooltip]::after {
    content: attr(data-tooltip);

    position: absolute;
    top: -20px;
    right: -20px;
    width: 150px;

    pointer-events: none;
    opacity: 0;
    -webkit-transition: opacity .15s ease-in-out;
    -moz-transition: opacity .15s ease-in-out;
    -ms-transition: opacity .15s ease-in-out;
    -o-transition: opacity .15s ease-in-out;
    transition: opacity .15s ease-in-out;

    display: block;
    font-size: 12px;
    line-height: 16px;
    background: #fefdcd;
    padding: 2px 2px;
    border: 1px solid #c0c0c0;
    box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.4);
}

*[data-tooltip]:hover::after {
    opacity: 1;
}

JavaScript opcional para cambiar la ubicación de la información sobre herramientas según la posición del ratón:

var style = document.createElement('style');
document.head.appendChild(style);

var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++) {
    var attr = allElements[i].getAttribute('data-tooltip');
    if (attr) {
        allElements[i].addEventListener('mouseover', hoverEvent);
    }
}

function hoverEvent(event) {
    event.preventDefault();
    x = event.x - this.offsetLeft;
    y = event.y - this.offsetTop;

    // Make it hang below the cursor a bit.
    y += 10;

    style.innerHTML = '*[data-tooltip]::after { left: ' + x + 'px; top: ' + y + 'px  }'

}

Respuesta #5

Aquí hay un bonito Tooltip de jQuery:

https://jqueryui.com/tooltip/

Para implementar esto, solo sigue estos pasos:

  1. Agrega este código en tus etiquetas <head></head>:

    <script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>    
    <script type="text/javascript">
    $("[title]").tooltip();
    </script> 
    <style type="text/css"> 
    
    /* tooltip styling. by default the element to be styled is .tooltip  */
    .tooltip {
        display:none;
        background:transparent url(https://dl.dropboxusercontent.com/u/25819920/tooltip/black_arrow.png);
        font-size:12px;
        height:70px;
        width:160px;
        padding:25px;
        color:#fff;
    }
    </style> 
    
  2. En los elementos HTML en los que quieras tener el tooltip, simplemente añade un atributo title a ellos. Cualquier texto que esté en el atributo title aparecerá en el tooltip.

Nota: Cuando JavaScript está desactivado, volverá al tooltip predeterminado del navegador/sistema operativo.

Respuesta #6

Hice algo que también debería poder adaptarse a un div.

HTML

<td>
    <%# (Eval("Name").ToString().Length > 65) ? Eval("Name").ToString().Substring(0, 60) + "..." : Eval("Name")%>
    <span class="showonhover">
        <a href="#"><%# (Eval("Name").ToString().Length > 65) ? "More" : "" %></a>
        <span class="hovertext">
            <%# Eval("Name") %>
        </span>
    </span>
</td>

CSS

.showonhover .hovertext { display: none;}
.showonhover:hover .hovertext {display: inline;}
a.viewdescription {color:#999;}
a.viewdescription:hover {background-color:#999; color: White;}
.hovertext {position:absolute;z-index:1000;border:1px solid #ffd971;background-color:#fffdce;padding:11px;width:150px;font-size: 0.75em;}

Para una discusión más detallada, vea mi publicación:

Un texto de herramienta con formato simple al pasar el cursor

Respuesta #7

De acuerdo, aquí están todos los requisitos de tu recompensa cumplidos:

  • Sin jQuery
  • Aparición instantánea
  • No desaparecer hasta que el ratón salga del área
  • Efecto de fundido de entrada/salida incorporado
  • Y por último... solución simple

Aquí hay una demostración y un enlace a mi código (JSFiddle)

Aquí están las características que he incorporado en este fiddle puramente de JS, CSS y HTML5:

  • Puedes ajustar la velocidad del desvanecimiento.
  • Puedes establecer el texto del tooltip con una variable sencilla.

HTML:

<div id="wrapper">
    <div id="a">Hover over this div to see a cool tool tip!</div>
</div>

CSS:

#a{
    background-color:yellow;
    padding:10px;
    border:2px solid red;    
}

.tooltip{
    background:black;
    color:white;
    padding:5px;
    box-shadow:0 0 10px 0 rgba(0, 0, 0, 1);
    border-radius:10px;
    opacity:0;
}

JavaScript:

var div = document.getElementById('wrapper');
var a = document.getElementById("a");
var fadeSpeed = 25; // a value between 1 and 1000 where 1000 will take 10
                    // seconds to fade in and out and 1 will take 0.01 sec.
var tipMessage = "The content of the tooltip...";

var showTip = function(){    
    var tip = document.createElement("span");
    tip.className = "tooltip";
    tip.id = "tip";
    tip.innerHTML = tipMessage;
    div.appendChild(tip);
    tip.style.opacity="0"; // to start with...
    var intId = setInterval(function(){
        newOpacity = parseFloat(tip.style.opacity)+0.1;
        tip.style.opacity = newOpacity.toString();
        if(tip.style.opacity == "1"){
            clearInterval(intId);
        }
    }, fadeSpeed);
};
var hideTip = function(){
    var tip = document.getElementById("tip");
    var intId = setInterval(function(){
        newOpacity = parseFloat(tip.style.opacity)-0.1;
        tip.style.opacity = newOpacity.toString();
        if(tip.style.opacity == "0"){
            clearInterval(intId);
            tip.remove();
        }
    }, fadeSpeed);
    tip.remove();
};

a.addEventListener("mouseover", showTip, false);
a.addEventListener("mouseout", hideTip, false);

Artículos relacionados