首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用jquery更改svg文本

使用jquery更改svg文本
EN

Stack Overflow用户
提问于 2016-10-31 22:37:36
回答 1查看 10.5K关注 0票数 3

我已经在网上浏览了整整两个小时,试图找到一个似乎很多人都有的问题的答案,但我找不到一个合适的解决方案。我需要更改svg文件中的文本,最终可能是浏览器中的文本输入。我设法使用了外部对象,但最终那不是我的问题的解决方案,因为我需要将它与路径对齐。

我的SVG

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg"     xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 841.9 595.3" style="enable-background:new 0 0 841.9 595.3;" xml:space="preserve">
<style type="text/css">
</style>
<text transform="matrix(1 0 0 1 325.2451 144.7144)" class="st0 st1" id="id-of-the-text">hey</text>
 <text class="testText" id="testText" x="10" y="20" style="fill:red;">Several lines:
    <tspan x="10" y="45">First line.</tspan>
    <tspan x="10" y="70">Second line.</tspan>
  </text>
  <text x="40" y="60">more text</text>
</svg>

以及类似问题的答案中失败的尝试

代码语言:javascript
运行
复制
$('#id-of-the-text').textContent = 'test';  
$("#id-of-the-text").text("new-value");  
$("#id-of-the-text")['innerText' in $("#id-of-the-text") ? "innerText" : "textContent"] = "some value";

这可能是一个愚蠢的小错误,否则我不能理解为什么我没有工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-01 16:42:11

使用text()应该是可行的。也许它失败是因为你的第一行有一个错误。

在任何情况下,请参阅我的示例以了解更改文本的各种方法。有些需要混合使用jQuery和DOM特性。

代码语言:javascript
运行
复制
// Change the first text element
$('#id-of-the-text').text("hey 2");  

// Change the first text node of the second text element.
// Have to do this a little differently. We need to be careful that we only change
// the first text node and that we don't replace everything including the tspans.
$("#testText").get(0).firstChild.textContent = "Several lines 2";

// Change the first tspan
$("#testText tspan:nth-child(1)").text("First line 2");

// Change the second tspan
// Alternative to using "nth-child(2)":
$("#testText tspan").last().text("Second line 2");

// Change the last text element
$("svg text").last().text("more text 2");
代码语言:javascript
运行
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg"     xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 841.9 595.3" style="enable-background:new 0 0 841.9 595.3;" xml:space="preserve">
  <style type="text/css">
  </style>

  <text transform="matrix(1 0 0 1 325.2451 144.7144)" class="st0 st1" id="id-of-the-text">hey</text>
   <text class="testText" id="testText" x="10" y="20" style="fill:red;">Several lines:
    <tspan x="10" y="45">First line.</tspan>
    <tspan x="10" y="70">Second line.</tspan>
  </text>
  <text x="40" y="60">more text</text>
</svg>

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40344387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档