gpt4 book ai didi

javascript - 如何使 SVG 中的文本可点击但不带下划线

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:46:14 25 4
gpt4 key购买 nike

我正在使用 JavaScript 将文本元素放入 SVG 元素中。我的动机是动态绘制一个包含文本的 Logo 。我想让整个 SVG 元素可点击以链接到另一个页面。这一切都有效,只是我不希望框中的文本像其他链接一样带有下划线。

下面的代码是一个精简版,演示了我正在尝试做的事情。如您所见,我注释掉了两个不同的 setAttribute() 调用;我都试过了,但都没有抑制下划线。

如有任何建议,我们将不胜感激。谢谢。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<title>Test SVG Text As Link</title>
<style>
.no-underline {
text-decoration:none;
}
</style>
<script>
// Defined symbolic constants
var SVG_NS = "http://www.w3.org/2000/svg";

/* Draws the box with text in it.
* Parameter:
* id = String containing the ID of the SVG element to draw into.
*/
function drawBox(id) {
var box = document.getElementById(id); // Find the SVG element
// How big should the text be?
var fontSize = '20px';
// Now make the text boxes
var line1 = makeText(20, 180, 50, 180,
'green', 1, 'green', fontSize, 'Arial', 'Some text');
//line1.setAttribute("style", "text-decoration:none");
//line1.setAttribute("class", ".no-underline");
box.appendChild(line1);
}

/*
* Constructs a textbox that can be added to the SVG
* element at (x, y)
*
* Parameters:
* x, y, height, width in pixels
* strokeColor, fillColor
* strokeWidth in pixels
* fontSize in points, presumably
* text
*
* Returns: The text element
*/
function makeText(x, y, height, width, strokeColor, strokeWidth,
fillColor, fontSize, fontFamily, text) {
var newBox = document.createElementNS(SVG_NS,"text");
newBox.setAttributeNS(null,"x", x);
newBox.setAttributeNS(null,"y", y);
newBox.setAttributeNS(null,"height", height);
newBox.setAttributeNS(null,"width", width);
newBox.setAttributeNS(null,"stroke", strokeColor);
newBox.setAttributeNS(null,"stroke-width", strokeWidth);
newBox.setAttributeNS(null,"fill", fillColor);
newBox.setAttributeNS(null,"font-size",fontSize);
newBox.setAttributeNS(null,"font-family", fontFamily);
newBox.textContent = text;
return newBox;
}
</script>
</head>
<a href="foo.html">
<body onload="drawBox('svgBox');" >
<svg width="200" height="200" id="svgBox">
</svg>
<br/>
Could also click here.
</a>
</body>
</html>

最佳答案

似乎是 FF 和 Chrome 中的错误。

解决方法是不要将 SVG 包装在 <a> 中元素。相反,把 <a>在 SVG 中,像这样:

<svg width="200" height="200" id="svgBox"
xmlns:xlink="http://www.w3.org/1999/xlink">
<a xlink:href="foo.html">
<text id="foo" x="20" y="180">Some text</text>
</a>
</svg>
<br/>
<a href="foo.html">
Could also click here.
</a>

然后您可以使用 CSS 禁用下划线。

Demo here

关于javascript - 如何使 SVG 中的文本可点击但不带下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25478183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com