如何获取javascript生成的标题工具提示以显示SVG [英] How to get javascript generated title tooltip for SVG to show up
问题描述
我正在尝试获取SVG元素的工具提示. (在Firefox 16.0.2下测试),我尝试了这个小例子,并且效果很好:
I'm trying to get a tooltip for an SVG element. (Testing under Firefox 16.0.2) I tried this little example and it works fine:
<svg xmlns="http://www.w3.org/2000/svg">
<rect id="test" x="20" y="30" width="200" height="150">
<title>Test tooltip</title>
</rect>
</svg>
但是,我需要从javascript生成工具提示,因为SVG也是从javascript生成的.因此,作为第一个测试,我尝试仅生成工具提示:
But, I need to generate the tooltip from javascript, as the SVG is also being generated from javascript. So just as a first test, I tried generating just the tooltip:
<script type="text/javascript">
function test(text) {
var title = document.createElement("title")
title.text = text
document.getElementById("test").appendChild(title)
}
</script>
</head>
<body onload="test('Test tooltip')">
<svg xmlns="http://www.w3.org/2000/svg">
<rect id="test" x="20" y="30" width="200" height="150">
</rect>
</svg>
当我检查Firefox的结果时,标题对象看起来与从HTML/SVG生成的标题相同,除了当我将鼠标悬停在矩形上时,没有工具提示!我在做什么错了?
When I inspect the results from Firefox the title objects appears identical to the title generated from the HTML/SVG, except that when I mouse over the rectangle there is no tooltip! What am I doing wrong?
推荐答案
title元素应位于SVG名称空间中,而不是默认名称空间中.因此,您应该使用createElementNS()
.此外,SVG标题元素不具有text
属性.使用textContent
代替.因此,这应该可行:
The title element should be in the SVG namespace, not the default namespace. Therefore, you should use createElementNS()
. Also, the SVG title element does not have the text
property. Use textContent
instead. So, this should work:
<script type="text/javascript">
function test(text) {
var title = document.createElementNS("http://www.w3.org/2000/svg","title")
title.textContent = text
document.getElementById("test").appendChild(title)
}
</script>
</head>
<body onload="test('Test tooltip')">
<svg xmlns="http://www.w3.org/2000/svg">
<rect id="test" x="20" y="30" width="200" height="150">
</rect>
</svg>
这篇关于如何获取javascript生成的标题工具提示以显示SVG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!