简体   繁体   English

设置工具提示文本与其元素分开

[英]Setting tooltip text separately from its element

I would like to add a tooltip description to all elements according to their CSS class(es). 我想根据其CSS类向所有元素添加工具提示说明。

I know tooltips are typically set using the title attribute of the element, but since I have many such elements and the description would be the same (and fairly long), I don't want to set it this way to avoid pointless bloat, so I would rather define the text once separately and then somehow associate it with the particular classes. 我知道通常使用该元素的title属性来设置工具提示,但是由于我有很多这样的元素,并且说明将是相同的(而且相当长),因此我不想以此方式设置它以避免无意义的膨胀,因此我宁愿单独定义一次文本,然后以某种方式将其与特定的类关联。

From what I've gathered so far, it doesn't seem to be possible using mere HTML+CSS, which would be the ideal, but a concise Javascript/jQuery solution would be good too. 从到目前为止的经验来看,仅使用HTML + CSS似乎是不可能的,这是理想的选择,但是简洁的Javascript / jQuery解决方案也将是不错的选择。 Does anyone know how to do this? 有谁知道如何做到这一点?

Bonus points if the text could be concatenated on elements with multiple classes. 如果文本可以串联到具有多个类的元素上,则加分。 :P :P

Using just CSS, you can try using this "tooltip" class: 仅使用CSS,您可以尝试使用此“工具提示”类:

.tooltip:after {
    display: none;
}

.tooltip:hover:after {
    display: inline;
    position: absolute;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-shadow: 1px 1px 4px #000;
    background-color: #fff;
    margin-left: 5px;
    margin-top: -25px;
    padding: 3px;
}

Then you give your elements a specific class , say "test". 然后,给您的元素指定一个特定的class ,说“测试”。 In your CSS, you then include: 然后,在CSS中包括:

.test:after {
    content: "Whatever text you want";
}

DEMO: http://jsfiddle.net/ec2Tx/ 演示: http : //jsfiddle.net/ec2Tx/

In the demo, I underlined the tooltip elements so you could see what to hover. 在演示中,我强调了工具提示元素,以便您可以看到要悬停的内容。

For future reference: Seeking a solution able to handle concatenation of tooltip text, I managed to come up with a simple jQuery one. 供将来参考:寻找一种能够处理工具提示文本串联的解决方案,我设法提出了一个简单的jQuery。 Basically, for each class requiring such a description, add: 基本上,对于需要此类说明的每个类,请添加:

$(".classX").hover(
    function() {
        var previous = $(this).attr('title') || '';
        var descr    = "description X"
        $(this).attr('title', previous + descr);
    }, function() { $(this).attr('title', ''); }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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