Is it possible to enhance the default appearance o

2019-02-23 03:30发布

问题:

I would like to change the default appearance of tooltip in svg elements (title) by any means such as js or css.

I even tried stuff like this:

var title = document.createElementNS('http://www.w3.org/2000/svg','title');
title.textContent='<foreignObject width="100" height="50" requiredExtensions="http://www.w3.org/1999/xhtml"><div style="background:blue;">'+arr[j].ypos+'</div><foreignObject>';
rect.appendChild(title);

but regardless of whatever i insert as the textContent of title, its simply rendered as a string.

Is there any way to style the default tooltip? Other simple and straightforward alternatives for creating tooltips in svg without using any plugins are also welcome...

回答1:

You could try this: How to change the style of Title attribute inside the anchor tag?. I didn't test it, so I don't really know if it works.

But since you are using SVG, you can do better than that since you can draw tooltips with any color and shape, even animated. Since you are generating it dynamically with a script, you can calculate the size based on the content and alter the height and width accordingly.

Here is an example of a tooltip using a rounded rectangle in SVG:

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <g id="component">
        <rect id="content" width="50" height="50">
        </rect>
        <g class="tooltip" transform="translate(20,20)" opacity="0.9">
            <rect rx="5" width="100" height="25"></rect>
            <text x="15" y="16">Hello</text>
        </g>
    </g>
</svg>

I used CSS hover to make it appear and disappear:

#component .tooltip {visibility: hidden}
#component:hover .tooltip {
    visibility: visible;
}
.tooltip text {
    fill: black;
    font-size: 12px;
    font-family: sans-serif;
}
.tooltip rect {
    fill: yellow;
    stroke: blue;
}

You can experiment with it in this JSFiddle.

You can also store your tooltips in a <defs> block and reuse it in different objects.