Snap.SVG-操作$(this)元素

时间:2018-10-17 14:17:03

标签: javascript jquery svg snap.svg

我对Snap.SVG和多个SVG元素的动画有问题。 我想在悬停时更改路径,但是我在html中有很多相同的SVG。

HTML:

   

var svg = $('.svg-wave');
var s = Snap(svg);

var simpleCup = Snap.select('.svg-wave-normal');
var fancyCup = Snap.select('.svg-wave-hover');

var simpleCupPoints = simpleCup.node.getAttribute('d');
var fancyCupPoints = fancyCup.node.getAttribute('d');

svg.mouseenter(function() {
  simpleCup.animate({
    d: fancyCupPoints
  }, 600);
}).mouseleave(function() {
  simpleCup.animate({
    d: simpleCupPoints
  }, 600);
});
svg .svg-wave-hover {opacity: 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.5.1/snap.svg-min.js"></script>
<div class="item">
  <svg class="svg-wave" width="240" height="120" viewBox="0 0 240 120" xmlns="http://www.w3.org/2000/svg">
                            <path class="svg-wave-normal" d="M108.5,114.8C71.7,114.8,62.7,117,0,117h217C151,117,146.2,114.8,108.5,114.8" fill="#69c6d3"></path>
                            <path class="svg-wave-hover"  d="M108.5,0C71.7,0,62.7,117,0,117h217C151,117,146.2,0,108.5,0" fill="#69c6d3"></path>
                        </svg>
  </div>
<div class="item">
  <svg class="svg-wave" width="240" height="120" viewBox="0 0 240 120" xmlns="http://www.w3.org/2000/svg">
                            <path class="svg-wave-normal" d="M108.5,114.8C71.7,114.8,62.7,117,0,117h217C151,117,146.2,114.8,108.5,114.8" fill="#69c6d3"></path>
                            <path class="svg-wave-hover"  d="M108.5,0C71.7,0,62.7,117,0,117h217C151,117,146.2,0,108.5,0" fill="#69c6d3"></path>
                        </svg>
  </div>
<div class="item">
  <svg class="svg-wave" width="240" height="120" viewBox="0 0 240 120" xmlns="http://www.w3.org/2000/svg">
                            <path class="svg-wave-normal" d="M108.5,114.8C71.7,114.8,62.7,117,0,117h217C151,117,146.2,114.8,108.5,114.8" fill="#69c6d3"></path>
                            <path class="svg-wave-hover"  d="M108.5,0C71.7,0,62.7,117,0,117h217C151,117,146.2,0,108.5,0" fill="#69c6d3"></path>
                        </svg>
</div>

问题在于,当我将鼠标悬停在上一个SVG上时,它将为第一个SVG设置动画。 有人可以帮我从$(this)更改mouseenter / leave的工作方式吗?

1 个答案:

答案 0 :(得分:0)

我将首先建议不使用JQuery的方法,因为这并不是必需的。

我将更改您的css以将鼠标悬停路径设置为display: none,而不是opacity: 0,因为不显示将表示事件将顺利进行,而不透明将捕获它们。或者,您可以重新排列路径,因此最偏路径优先。

var normalWaves = Snap.selectAll('.svg-wave-normal');
var normalPoints = Snap.select('.svg-wave-normal').attr('d');
var hoverPoints = Snap.select('.svg-wave-hover').attr('d');

normalWaves.forEach(function( wave ) {
  wave.mouseover(function() {
    this.animate({
      d: hoverPoints
    }, 600); 
  })
  .mouseout(function() {
    this.animate({
      d: normalPoints
    }, 600);
  });
});

svg .svg-wave-hover { display: none; }

jsfiddle