簡體   English   中英

如何在SVG中使文本可單擊但不加下划線

[英]How To Make Text In SVG Clickable But Not Underlined

我正在使用JavaScript將文本元素放在SVG元素中。 我的動機是動態繪制包含文本的徽標。 我想讓整個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禁用下划線。

在這里演示

好吧,我好像現在都在工作。 我最后做的是將整個SVG包裝在一個錨(“a”)標簽中,並手動放入'style =“text-decoration:none;” '錨標記中的屬性,而不是內部文本(通過“手動”,我的意思是我將其鍵入HTML而不是使用JavaScript生成)。 像這樣:

<a href="foo.html" style="text-decoration:none">
<svg ...> Everything inside here will get added by JavaScript
</svg>
</a>

感謝大家的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM