【问题标题】:Moving <text> around within an svg element在 svg 元素内移动 <text>
【发布时间】:2015-11-02 21:22:30
【问题描述】:

我正在尝试在 SVG 图形上叠加一个元素。为简单起见,我将它重新创建为一个带有文本覆盖的矩形。我将对文本进行一些非常严肃的格式化和样式设置,但现在我正试图弄清楚为什么我不能在页面上将它放低。我尝试更改元素上的“x”和“y”,但它根本不动。任何人都可以帮忙吗?我想将黄色 SVG 矩形中的文本向下移动。

这里是完整的代码:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Title Here</title>
  <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  <style type="text/css">

    ul {
        position:absolute;
     }
  </style>
</head>

<body>
  <p>Click me</p>
  <ul><text x="40" y="90">Test</text></ul>
  <script type="text/javascript">
    //Width and height
    var w = 500;
    var h = 300;
    var padding = 30;


    //Create SVG element
    var svg = d3.select("body")
      .append("svg")
      .attr("width", w)
      .attr("height", h)

      svg.append("rect")
        .attr("width", w)
        .attr("height", h)
        .attr("fill", "yellow");

  </script>
</body>

</html>

【问题讨论】:

    标签: javascript css d3.js svg


    【解决方案1】:

    text 是一个svg 元素,必须包含在svg 标记中。

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8" />
      <title>Title Here</title>
      <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
      <style type="text/css">
        ul {
          position: absolute;
          padding: 0;
        }
      </style>
    </head>
    
    <body>
      <p>Click me</p>
      <ul>
        <svg width="500" height="300" viewBox="0 0 500 300">
          <text x="40" y="270">Test</text>
        </svg>
      </ul>
      <script type="text/javascript">
        //Width and height
        var w = 500;
        var h = 300;
        var padding = 30;
    
    
         //Create SVG element
        var svg = d3.select("body")
          .append("svg")
          .attr("width", w)
          .attr("height", h)
    
         svg.append("rect")
          .attr("width", w)
          .attr("height", h)
          .attr("fill", "yellow");
      </script>
    </body>
    
    </html>

    【讨论】:

    • 谢谢!这很容易:)
    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2021-12-01
    • 1970-01-01
    • 2015-10-03
    相关资源
    最近更新 更多