SVG文本动态添加title标签后鼠标悬停不显示问题求助
解决SVG动态添加title不显示的问题
嘿,这个问题我之前也踩过坑!原因其实很直白:你用document.createElement("title")创建的是HTML命名空间的title元素,但SVG里的title属于专属的SVG命名空间,浏览器没法把HTML的title当成SVG的悬停提示来处理,所以悬停时完全没反应。而静态写在SVG标签里的title,浏览器会自动识别为SVG命名空间的元素,自然就能正常生效。
修复方案
只需要把创建title元素的方式换成document.createElementNS,指定SVG的官方命名空间http://www.w3.org/2000/svg就搞定了。修改后的appendTitle函数如下:
function appendTitle() { try { // 使用SVG命名空间创建title元素 var node = document.createElementNS("http://www.w3.org/2000/svg", "title"); node.textContent = "I love SVG"; document.getElementById("abcd").appendChild(node); } catch (e) { console.error(e); // 加个错误日志方便排查问题 } }
完整可运行代码
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> <script> function appendTitle() { try { var node = document.createElementNS("http://www.w3.org/2000/svg", "title"); node.textContent = "I love SVG"; document.getElementById("abcd").appendChild(node); } catch (e) { console.error(e); } } </script> </head> <body> <svg height="30" width="200"> <text x="0" y="15" fill="red" id="abcd"> I love SVG! </text> </svg> <button onclick="appendTitle()">click</button> </body>
点击按钮后,再悬停SVG文本,就能正常看到悬停提示啦!
内容的提问来源于stack exchange,提问作者affu
相关产品推荐
相关产品推荐

