Html 如何更改锚标记内标题属性的样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2011142/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:47:14  来源:igfitidea点击:

How to change the style of the title attribute inside an anchor tag?

htmlcss

提问by Kunpha

Example:

例子:

<a href="example.com" title="My site"> Link </a>

How do I change the presentation of the "title" attribute in the browser?. By default, it just has yellow background and small font. I would like to make it bigger and change the background color.

如何更改浏览器中“title”属性的显示?默认情况下,它只有黄色背景和小字体。我想让它变大并改变背景颜色。

Is there a CSS way to style the title attribute?

是否有 CSS 方法来设置标题属性的样式?

回答by valli

Here is an example of how to do it:

以下是如何执行此操作的示例:

a.tip {
    border-bottom: 1px dashed;
    text-decoration: none
}
a.tip:hover {
    cursor: help;
    position: relative
}
a.tip span {
    display: none
}
a.tip:hover span {
    border: #c0c0c0 1px dotted;
    padding: 5px 20px 5px 5px;
    display: block;
    z-index: 100;
    background: url(../images/status-info.png) #f0f0f0 no-repeat 100% 5%;
    left: 0px;
    margin: 10px;
    width: 250px;
    position: absolute;
    top: 10px;
    text-decoration: none
}
<a href="#" class="tip">Link<span>This is the CSS tooltip showing up when you mouse over the link</span></a>

回答by Jon z

It seems that there is in fact a pure CSS solution, requiring only the css attrexpression, generated content and attribute selectors (which suggests that it works as far back as IE8):

似乎实际上有一个纯 CSS 解决方案,只需要 cssattr表达式、生成的内容和属性选择器(这表明它可以追溯到 IE8):

a[title]:hover:after {
  content: attr(title);
  position: absolute;
}

Source: https://jsfiddle.net/z42r2vv0/2/

来源:https: //jsfiddle.net/z42r2vv0/2/

updatew/ input from @ViROscar: please note that it's not necessary to use any specific attribute, although I've used the "title" attribute in the example above; actually my recommendation would be to use the "alt" attribute, as there is some chance that the content will be accessible to users unable to benefit from CSS.

更新来自@ViROscar 的输入:请注意,虽然我在上面的示例中使用了“title”属性,但没有必要使用任何特定属性;实际上,我的建议是使用“alt”属性,因为有可能无法从 CSS 中受益的用户可以访问内容。

update againI'm not changing the code because the "title" attribute has basically come to mean the "tooltip" attribute, and it's probably not a good idea to hide important text inside a field only accessible on hover, but if you're interested in making this text accessible the "aria-label" attribute seems like the best place for it: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute

再次更新我没有更改代码,因为“标题”属性基本上已经意味着“工具提示”属性,并且将重要文本隐藏在只能在悬停时访问的字段中可能不是一个好主意,但是如果您是有兴趣使此文本可访问“aria-label”属性似乎是它的最佳位置:https: //developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute

回答by Makyen

You can't style an actual titleattribute

您无法为实际title属性设置样式

How the text in the titleattribute is displayed is defined by the browser and varies from browser to browser. It's not possible for a webpage to apply any style to the tooltip that the browser displays based on the titleattribute.

如何在文本title显示的属性是由浏览器定义,并从不同的浏览器到浏览器。网页不可能根据title属性对浏览器显示的工具提示应用任何样式。

However, you can create something very similar using other attributes.

但是,您可以使用其他属性创建非常相似的内容。

You can make a pseudo-tooltip with CSS and a custom attribute (e.g. data-title)

您可以使用 CSS 和自定义属性制作伪工具提示(例如data-title

For this, I'd use a data-titleattribute. data-*attributesare a method to store custom data in DOM elements/HTML. There are multiple ways of accessing them. Importantly, they can be selected by CSS.

为此,我会使用一个data-title属性。data-*属性是一种在 DOM 元素/HTML 中存储自定义数据的方法。有多种方法可以访问它们。重要的是,它们可以由 CSS 选择。

Given that you can use CSS to select elements with data-titleattributes, you can then use CSS to create :after(or :before) contentthat contains the value of the attribute using attr().

鉴于您可以使用 CSS 来选择具有data-title属性的元素,然后您可以使用 CSS 创建:after(或:beforecontent包含使用attr().

Styled tooltip Examples

样式化工具提示示例

Bigger and with a different background color (per question's request):

更大并具有不同的背景颜色(根据问题的要求):

[data-title]:hover:after {
    opacity: 1;
    transition: all 0.1s ease 0.5s;
    visibility: visible;
}
[data-title]:after {
    content: attr(data-title);
    background-color: #00FF00;
    color: #111;
    font-size: 150%;
    position: absolute;
    padding: 1px 5px 2px 5px;
    bottom: -1.6em;
    left: 100%;
    white-space: nowrap;
    box-shadow: 1px 1px 3px #222222;
    opacity: 0;
    border: 1px solid #111111;
    z-index: 99999;
    visibility: hidden;
}
[data-title] {
    position: relative;
}
<a href="example.com" data-title="My site"> Link </a> with styled tooltip (bigger and with a different background color, as requested in the question)<br/>
<a href="example.com" title="My site"> Link </a> with normal tooltip

More elaborate styling (adapted from this blog post):

更精致的样式(改编自这篇博文):

[data-title]:hover:after {
    opacity: 1;
    transition: all 0.1s ease 0.5s;
    visibility: visible;
}
[data-title]:after {
    content: attr(data-title);
    position: absolute;
    bottom: -1.6em;
    left: 100%;
    padding: 4px 4px 4px 8px;
    color: #222;
    white-space: nowrap; 
    -moz-border-radius: 5px; 
    -webkit-border-radius: 5px;  
    border-radius: 5px;  
    -moz-box-shadow: 0px 0px 4px #222;  
    -webkit-box-shadow: 0px 0px 4px #222;  
    box-shadow: 0px 0px 4px #222;  
    background-image: -moz-linear-gradient(top, #f8f8f8, #cccccc);  
    background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #f8f8f8),color-stop(1, #cccccc));
    background-image: -webkit-linear-gradient(top, #f8f8f8, #cccccc);  
    background-image: -moz-linear-gradient(top, #f8f8f8, #cccccc);  
    background-image: -ms-linear-gradient(top, #f8f8f8, #cccccc);  
    background-image: -o-linear-gradient(top, #f8f8f8, #cccccc);
    opacity: 0;
    z-index: 99999;
    visibility: hidden;
}
[data-title] {
    position: relative;
}
<a href="example.com" data-title="My site"> Link </a> with styled tooltip<br/>
<a href="example.com" title="My site"> Link </a> with normal tooltip

Known issues

已知的问题

Unlike a real titletooltip, the tooltip produced by the above CSS is not, necessarily, guaranteed to be visible on the page (i.e. it might be outside the visible area). On the other hand, it is guaranteed to be within the current window, which is not the case for an actual tooltip.

与真正的title工具提示不同,由上述 CSS 生成的工具提示不一定保证在页面上可见(即它可能在可见区域之外)。另一方面,它保证在当前窗口内,实际的工具提示不是这种情况。

In addition, the pseudo-tooltip is positioned relative to the element that has the pseudo-tooltip rather than relative to where the mouse is on that element. You may want to fine-tune where the pseudo-tooltip is displayed. Having it appear in a known location relative to the element can be a benefit or a drawback, depending on the situation.

此外,伪工具提示相对于具有伪工具提示的元素定位,而不是相对于鼠标在该元素上的位置。您可能需要微调伪工具提示的显示位置。让它出现在相对于元素的已知位置可能是一个好处也可能是一个缺点,这取决于具体情况。

You can't use :beforeor :afteron elements which are not containers

您不能在不是容器的元素上使用:before:after

There's a good explanation in this answer to "Can I use a :before or :after pseudo-element on an input field?"

这个答案中有一个很好的解释“我可以在输入字段上使用 :before 或 :after 伪元素吗?”

Effectively, this means that you can't use this method directly on elements like <input type="text"/>, <textarea/>, <img>, etc. The easy solution is to wrap the element that's not a container in a <span>or <div>and have the pseudo-tooltip on the container.

有效地,这意味着,你不能像元件直接使用这个方法<input type="text"/><textarea/><img>等。简单的解决方案是包装,这不是一个容器内的元件在一个<span><div>和具有在容器上的伪工具提示。

Examples of using a pseudo-tooltip on a <span>wrapping a non-container element:

<span>包装非容器元素上使用伪工具提示的示例:

[data-title]:hover:after {
    opacity: 1;
    transition: all 0.1s ease 0.5s;
    visibility: visible;
}
[data-title]:after {
    content: attr(data-title);
    background-color: #00FF00;
    color: #111;
    font-size: 150%;
    position: absolute;
    padding: 1px 5px 2px 5px;
    bottom: -1.6em;
    left: 100%;
    white-space: nowrap;
    box-shadow: 1px 1px 3px #222222;
    opacity: 0;
    border: 1px solid #111111;
    z-index: 99999;
    visibility: hidden;
}
[data-title] {
    position: relative;
}

.pseudo-tooltip-wrapper {
    /*This causes the wrapping element to be the same size as what it contains.*/
    display: inline-block;
}
Text input with a pseudo-tooltip:<br/>
<span class="pseudo-tooltip-wrapper" data-title="input type=&quot;text&quot;"><input type='text'></span><br/><br/><br/>
Textarea with a pseudo-tooltip:<br/>
<span class="pseudo-tooltip-wrapper" data-title="this is a textarea"><textarea data-title="this is a textarea"></textarea></span><br/>



From the code on the blog post linked above (which I first saw in an answer here that plagiarized it), it appeared obvious to me to use a data-*attribute instead of the titleattribute. Doing so was also suggested in a comment by snostormon that (now deleted) answer.

从上面链接的博客文章中的代码(我第一次在此处看到抄袭它的答案中看到),对我来说使用data-*属性而不是title属性似乎很明显。snostorm在对该(现已删除)答案的评论中也建议这样做。

回答by cletus

CSS can't change the tooltip appearance. It is browser/OS-dependent. If you want something different you'll have to use Javascript to generate markup when you hover over the element instead of the default tooltip.

CSS 无法更改工具提示外观。它依赖于浏览器/操作系统。如果你想要一些不同的东西,当你将鼠标悬停在元素而不是默认工具提示上时,你必须使用 Javascript 来生成标记。

回答by ChrisF

I thought i'd post my 20 lines JavaScript solution here. It is not perfect, but may be useful for some depending on what you need from your tooltips.

我想我会在这里发布我的 20 行 JavaScript 解决方案。它并不完美,但可能对某些人有用,具体取决于您对工具提示的需求。

When to use it

何时使用

  • Automatically styles the tooltip for all HTML elements with a TITLEattribute defined (this includes elements dynamically added to the document in the future)
  • No Javascript/HTML changes or hacks required for every tooltip (just the TITLEattribute, semantically clear)
  • Very light (adds about 300 bytes gzipped and minified)
  • You want only a very basic styleable tooltip
  • 使用TITLE定义的属性自动设置所有 HTML 元素的工具提示样式(这包括将来动态添加到文档的元素)
  • 每个工具提示都不需要 Javascript/HTML 更改或黑客攻击(只是TITLE属性,语义清晰)
  • 非常轻(添加大约 300 字节的压缩和缩小)
  • 您只需要一个非常基本的样式化工具提示

When NOT to use

何时不使用

  • Requires jQuery, so do not use if you don't use jQuery
  • Bad support for nested elements that both have tooltips
  • You need more than one tooltip on the screen at the same time
  • You need the tooltip to disappear after some time
  • 需要 jQuery,所以如果你不使用 jQuery,就不要使用
  • 对都有工具提示的嵌套元素的支持不好
  • 您需要同时在屏幕上显示多个工具提示
  • 您需要工具提示在一段时间后消失

The code

编码

// Use a closure to keep vars out of global scope
(function () {
    var ID = "tooltip", CLS_ON = "tooltip_ON", FOLLOW = true,
    DATA = "_tooltip", OFFSET_X = 20, OFFSET_Y = 10,
    showAt = function (e) {
        var ntop = e.pageY + OFFSET_Y, nleft = e.pageX + OFFSET_X;
        $("#" + ID).html($(e.target).data(DATA)).css({
            position: "absolute", top: ntop, left: nleft
        }).show();
    };
    $(document).on("mouseenter", "*[title]", function (e) {
        $(this).data(DATA, $(this).attr("title"));
        $(this).removeAttr("title").addClass(CLS_ON);
        $("<div id='" + ID + "' />").appendTo("body");
        showAt(e);
    });
    $(document).on("mouseleave", "." + CLS_ON, function (e) {
        $(this).attr("title", $(this).data(DATA)).removeClass(CLS_ON);
        $("#" + ID).remove();
    });
    if (FOLLOW) { $(document).on("mousemove", "." + CLS_ON, showAt); }
}());

Paste it anywhere, it should work even when you run this code before the DOM is ready (it just won't show your tooltips until DOM is ready).

将它粘贴到任何地方,即使您在 DOM 准备好之前运行此代码,它也应该可以工作(在 DOM 准备好之前它不会显示您的工具提示)。

Customize

定制

You can change the vardeclarations on the second line to customize it a bit.

您可以更改var第二行的声明以对其进行一些自定义。

var ID = "tooltip"; // The ID of the styleable tooltip
var CLS_ON = "tooltip_ON"; // Does not matter, make it somewhat unique
var FOLLOW = true; // TRUE to enable mouse following, FALSE to have static tooltips
var DATA = "_tooltip"; // Does not matter, make it somewhat unique
var OFFSET_X = 20, OFFSET_Y = 10; // Tooltip's distance to the cursor

Style

风格

You can now style your tooltips using the following CSS:

您现在可以使用以下 CSS 设置工具提示样式:

#tooltip {
    background: #fff;
    border: 1px solid red;
    padding: 3px 10px;
}

回答by Andrés Chandía

I have found the answer here: http://www.webdesignerdepot.com/2012/11/how-to-create-a-simple-css3-tooltip/

我在这里找到了答案:http: //www.webdesignerdepot.com/2012/11/how-to-create-a-simple-css3-tooltip/

my own code goes like this, I have changed the attribute name, if you maintain the title name for the attribute you end up having two popups for the same text, another change is that my text on hovering displays underneath the exposed text.

我自己的代码是这样的,我已经更改了属性名称,如果您维护属性的标题名称,您最终会为相同的文本提供两个弹出窗口,另一个更改是我的悬停文本显示在暴露的文本下方。

.tags {
  display: inline;
  position: relative;
}

.tags:hover:after {
  background: #333;
  background: rgba(0, 0, 0, .8);
  border-radius: 5px;
  bottom: -34px;
  color: #fff;
  content: attr(glose);
  left: 20%;
  padding: 5px 15px;
  position: absolute;
  z-index: 98;
  width: 350px;
}

.tags:hover:before {
  border: solid;
  border-color: #333 transparent;
  border-width: 0 6px 6px 6px;
  bottom: -4px;
  content: "";
  left: 50%;
  position: absolute;
  z-index: 99;
}
<a class="tags" glose="Text shown on hovering">Exposed text</a>

回答by prasun

A jsfiddle for custom tooltip pattern is Here

自定义工具提示模式的 jsfiddle在这里

It is based on CSS Positioning and pseduo class selectors

它基于 CSS 定位和伪类选择器

Check MDN docsfor cross-browser support of pseudo classes

检查MDN 文档以获得伪类的跨浏览器支持

    <!-- HTML -->
<p>
    <a href="http://www.google.com/" class="tooltip">
    I am a 
        <span> (This website rocks) </span></a>&nbsp; a developer.
</p>

    /*CSS*/
a.tooltip {
    position: relative;
}

a.tooltip span {
    display: none;    
}

a.tooltip:hover span, a.tooltip:focus span {
    display:block;
    position:absolute;
    top:1em;
    left:1.5em;
    padding: 0.2em 0.6em;
    border:1px solid #996633;
    background-color:#FFFF66;
    color:#000;
}

回答by poncha

Native tooltip cannot be styled.

无法设置原生工具提示的样式。

That being said, you can use some library that would show styles floating layers when element is being hovered (instead of the native tooltips, and suppress them) requiring little or no code modifications...

话虽如此,您可以使用一些库,当元素被悬停时显示样式浮动层(而不是本机工具提示,并抑制它们)需要很少或不需要代码修改......

回答by bfavaretto

You cannot style the default browser tooltip. But you can use javascript to create your own custom HTML tooltips.

您无法设置默认浏览器工具提示的样式。但是您可以使用 javascript 来创建您自己的自定义 HTML 工具提示。

回答by shana.

a[title="My site"] {
    color: red;
}

This also works with any attribute you want to add for instance:

这也适用于您要添加的任何属性,例如:

HTML

HTML

<div class="my_class" anything="whatever">My Stuff</div>

CSS

CSS

.my_class[anything="whatever"] {
    color: red;
}

See it work at: http://jsfiddle.net/vpYWE/1/

看到它在:http: //jsfiddle.net/vpYWE/1/