javascript - 如何在 <text> 元素中使用 CSS 过渡效果?

标签 javascript html css

我正在使用 svg 制作图表,并且想让事情看起来更漂亮。
在我的图表中,我有一个 <circle><text>在里面,圆圈在移动。
我使用过渡使我的圆圈移动得漂亮,但不能与 <text> 一起使用tags
文字走出圆圈,圆圈在移动。

我该怎么做才能使文本跟在圆形元素之后?

笨蛋:https://plnkr.co/edit/iQZL1Pb4ozY80uFsVJaQ

var x = true;
var test = function() {

  var circleEl = document.getElementById('circle');

  var textEl = document.getElementById('text');

  if (x) {
    circleEl.setAttribute('cx', '400')
    textEl.setAttribute('x', '397')
    x = false
  } else {
    circleEl.setAttribute('cx', '50')
    textEl.setAttribute('x', '47')
    x = true
  }

}
.circle-transition {
  transition-property: all;
  transition-duration: 3s;
  transition-timing-function: linear;
}

.text-transition {
  transition-property: all;
  transition-duration: 3s;
  transition-timing-function: linear;
}
<svg width="1000px" heigth="200px">
    		<circle class="circle-transition" id="circle" r="10px" cy="50" cx="50" fill="red"></circle>
    		<text class="text-transition" id="text" y="55" x="47">1</text>
    	</svg>

<button onclick="test()">test it!</button>

最佳答案

使用SVG presentation attributes 需要谨慎一些并使用 CSS 为它们制作动画。例如,您的问题描述仅适用于 Chrome。在 Firefox 中,圆圈和文本都会跳动。

最好只使用 CSS 样式属性,在本例中为 transform。此外,您可以将元素组合在一起,这样只需要一个动画:

var x = true;
var test = function() {

  var groupEl = document.getElementById('group');

  if (x) {
    groupEl.setAttribute('style', 'transform:translate(350px)')
    x = false
  } else {
    groupEl.setAttribute('style', 'transform:translate(0px)')
    x = true
  }

}
.group-transition {
  transition-property: all;
  transition-duration: 3s;
  transition-timing-function: linear;
}
<svg width="1000px" heigth="200px">
     <g id="group" class="group-transition" style="transform:translate(0px)">
    		<circle id="circle" r="10px" cy="50" cx="50" fill="red"></circle>
    		<text id="text" y="55" x="47">1</text>
    </g>
</svg>

<button onclick="test()">test it!</button>

关于javascript - 如何在 <text> 元素中使用 CSS 过渡效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213853/

相关文章:

html - Bootstrap 响应式布局不适用于 Calc CSS 功能

html - 图像之间的差距?

Javascript:在除一个 div 之外的任何 div 上 onmousedown 时运行函数

html - 如何将搜索按钮对齐到搜索框的右侧

javascript - 将 HTML/CSS 元素导入可视化前端编辑器

php - CSS 未从 header.php 调用

html - 根据其他元素是否重叠更改元素的 z-index

javascript - 当我将它作为参数传递时,为什么 JavaScript 函数会自动转换二进制数?

javascript - 让谷歌美化与动态 View 博客模板一起工作

javascript - 突出显示表格日期时出错