Javascript 向 div 添加工具提示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7117073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a tooltip to a div
提问by user475685
I have a div tag like this:
我有一个像这样的 div 标签:
<div>
<label>Name</label>
<input type="text"/>
</div>
How can I displaying a tooltip on :hover
of the div, preferably with a fade in/out effect.
如何:hover
在 div上显示工具提示,最好具有淡入/淡出效果。
回答by sscirrus
For the basic tooltip, you want:
对于基本工具提示,您需要:
<div title="This is my tooltip">
For a fancier javascript version, you can look into:
对于更高级的 javascript 版本,您可以查看:
https://jqueryhouse.com/best-jquery-tooltip-plugins/
https://jqueryhouse.com/best-jquery-tooltip-plugins/
The above link gives you 25 options for tooltips.
上面的链接为您提供了 25 个工具提示选项。
回答by Andrea Ligios
It can be done with CSS only, no javascript at all: running demo
这是可以做到只用CSS,JavaScript的没有在所有:运行演示
Apply a custom HTML attribute, eg.
data-tooltip="bla bla"
to your object (div or whatever):<div data-tooltip="bla bla"> something here </div>
Define the
:before
pseudoelement of each[data-tooltip]
object to be transparent, absolutely positioned and withdata-tooltip=""
value as content:[data-tooltip]:before { position : absolute; content : attr(data-tooltip); opacity : 0; }
Define
:hover:before
hovering state of each[data-tooltip]
to make it visible:[data-tooltip]:hover:before { opacity : 1; }
Apply your styles (color, size, position etc) to the tooltip object; end of the story.
应用自定义 HTML 属性,例如。
data-tooltip="bla bla"
到您的对象(div 或其他):<div data-tooltip="bla bla"> something here </div>
将
:before
每个[data-tooltip]
对象的伪元素定义为透明、绝对定位且以data-tooltip=""
value 为内容:[data-tooltip]:before { position : absolute; content : attr(data-tooltip); opacity : 0; }
定义
:hover:before
每个悬停状态[data-tooltip]
以使其可见:[data-tooltip]:hover:before { opacity : 1; }
将您的样式(颜色、大小、位置等)应用到工具提示对象;故事的结局。
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, data-tooltip-persistent
, and a simple rule:
在演示中,我定义了另一个规则来指定工具提示在悬停在它上面但在父级之外时是否必须消失,还有另一个自定义属性data-tooltip-persistent
,和一个简单的规则:
[data-tooltip]:not([data-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.
注 1:浏览器对此的覆盖范围非常广泛,但请考虑对旧 IE 使用 javascript 回退(如果需要)。
Note 2:an enhancement might 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.
注 2:增强功能可能是添加一些 javascript 来计算鼠标位置并将其添加到伪元素中,方法是更改应用于它的类。
回答by cdhowie
You don't need JavaScript for this at all; just set the title
attribute:
你根本不需要 JavaScript。只需设置title
属性:
<div title="Hello, World!">
<label>Name</label>
<input type="text"/>
</div>
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.
请注意,工具提示的视觉呈现取决于浏览器/操作系统,因此它可能会淡入,也可能不会。但是,这是制作工具提示的语义方式,它可以与屏幕阅读器等辅助功能软件一起正常工作。
Demo in Stack Snippets
堆栈片段中的演示
<div title="Hello, World!">
<label>Name</label>
<input type="text"/>
</div>
回答by Nathan
Here's a nice jQuery Tooltip:
这是一个很好的 jQuery 工具提示:
To implement this, just follow these steps:
要实现这一点,只需按照以下步骤操作:
Add this code in your
<head></head>
tags:<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>
On the HTML elements that you want to have the tooltip, just add a
title
attribute to it. Whatever text is in the title attribute will be in the tooltip.
将此代码添加到您的
<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>
在您想要拥有工具提示的 HTML 元素上,只需
title
为其添加一个属性即可。title 属性中的任何文本都将出现在工具提示中。
Note:When JavaScript is disabled, it will fallback to the default browser/operating system tooltip.
注意:当 JavaScript 被禁用时,它将回退到默认浏览器/操作系统工具提示。
回答by Narnian
I did something that should be able to be adapted to a div as well.
我做了一些应该能够适应 div 的事情。
HTML
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
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;}
For a more in-depth discussion, see my post:
有关更深入的讨论,请参阅我的帖子:
回答by Steven Linn
Here's a pure CSS 3implementation (with optional JS)
这是一个纯 CSS 3实现(带有可选的 JS)
The only thing you have to do is set an attribute on any div called "data-tooltip" and that text will be displayed next to it when you hover over it.
您唯一需要做的就是在任何名为“data-tooltip”的 div 上设置一个属性,当您将鼠标悬停在它上面时,该文本将显示在它旁边。
I've included some optional JavaScript that will cause the tooltip to be displayed near the cursor. If you don't need this feature, you can safely ignore the JavaScript portion of this fiddle.
我已经包含了一些可选的 JavaScript,它们会导致工具提示显示在光标附近。如果您不需要此功能,则可以放心地忽略此小提琴的 JavaScript 部分。
If you don't want the fade-in on the hover state, just remove the transition properties.
如果您不想在悬停状态上淡入,只需删除过渡属性。
It's styled like the title
property tooltip. Here's the JSFiddle: http://jsfiddle.net/toe0hcyn/1/
它的样式类似于title
属性工具提示。这是 JSFiddle:http: //jsfiddle.net/toe0hcyn/1/
HTML Example:
HTML 示例:
<div data-tooltip="your tooltip message"></div>
CSS:
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;
}
Optional JavaScript for mouse position-based tooltip location change:
用于基于鼠标位置的工具提示位置更改的可选 JavaScript:
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 }'
}
回答by Anshu Dwibhashi
Okay, here's all of your bounty requirements met:
好的,这是您满足的所有赏金要求:
- No jQuery
- Instant appearing
- No dissapearing until the mouse leaves the area
- Fade in/out effect incorporated
- And lastly.. simple solution
- 没有 jQuery
- 瞬间出现
- 在鼠标离开该区域之前不会消失
- 加入淡入/淡出效果
- 最后..简单的解决方案
Here's a demo and link to my code (JSFiddle)
Here are the features that I've incorporated into this purely JS, CSS and HTML5 fiddle:
以下是我在这个纯 JS、CSS 和 HTML5 小提琴中加入的功能:
- You can set the speed of the fade.
- You can set the text of the tooltip with a simple variable.
- 您可以设置淡入淡出的速度。
- 您可以使用简单的变量设置工具提示的文本。
HTML:
HTML:
<div id="wrapper">
<div id="a">Hover over this div to see a cool tool tip!</div>
</div>
CSS:
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:
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);
回答by Clint Brown
You can create custom CSS tooltips using a data attribute, pseudo elements and content: attr()
eg.
您可以使用数据属性、伪元素等创建自定义 CSS 工具提示content: attr()
。
http://jsfiddle.net/clintioo/gLeydk0k/11/
http://jsfiddle.net/clintioo/gLeydk0k/11/
<div data-tooltip="This is my tooltip">
<label>Name</label>
<input type="text" />
</div>
.
.
div:hover:before {
content: attr(data-tooltip);
position: absolute;
padding: 5px 10px;
margin: -3px 0 0 180px;
background: orange;
color: white;
border-radius: 3px;
}
div:hover:after {
content: '';
position: absolute;
margin: 6px 0 0 3px;
width: 0;
height: 0;
border-top: 5px solid transparent;
border-right: 10px solid orange;
border-bottom: 5px solid transparent;
}
input[type="text"] {
width: 125px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
回答by ProllyGeek
You can toggle a child div during onmouseover
and onmouseout
like this:
您可以在切换孩子的divonmouseover
和onmouseout
如下:
function Tooltip(el, text) {
el.onmouseover = function() {
el.innerHTML += '<div class="tooltip">' + text + '</div>'
}
el.onmouseout = function() {
el.removeChild(el.querySelector(".tooltip"))
}
}
//Sample Usage
Tooltip(document.getElementById("mydiv"),"hello im a tip div")
Example in Stack Snippets & jsFiddle
Stack Snippets 和jsFiddle 中的示例
function Tooltip(el, text) {
el.onmouseover = function() {
el.innerHTML += '<div class="tooltip">' + text + '</div>'
}
el.onmouseout = function() {
el.removeChild(el.querySelector(".tooltip"))
}
}
//Sample Usage
Tooltip(document.getElementById("mydiv"), "I'm a tooltip")
#mydiv {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 120px;
height: 50px;
padding: 5px 10px;
background-color: #e2f7ff;
box-shadow: 1px 1px 1px 0px #cecece;
}
.tooltip {
position: absolute;
display: inline-block;
white-space: nowrap;
width: auto;
height: auto;
background-color: #11121b;
color: white;
padding: 4px 6px;
border-radius: 3px;
z-index: 99;
left: 100%;
top: 0;
}
<div id="mydiv"> This is just a div </div>
回答by designcise
The simplest way would be to set position: relative
on the containing element and position: absolute
on the tooltip element inside the container to make it float relative to the parent (containing element). For example:
最简单的方法是在容器内position: relative
的包含元素和position: absolute
工具提示元素上设置,使其相对于父元素(包含元素)浮动。例如:
<div style="background: yellow;">
<div style="display: inline-block; position: relative; background: pink;">
<label>Name</label>
<input type="text" />
<div style="background: #e5e5e5; position: absolute; top: -10px; left: 0; right: 0;">
Tooltip text
</div>
</div>
</div>