2017-09-06 71 views
0

使用Anime.js我想在懸停時變形SVG。我可以使這個工作正常,但是我很難弄清楚如何使相同的腳本適用於頁面上的多個元素。 JSFiddle將動畫SVG懸停在相對目標上

<a class="link" href="#"> 
    <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"> 
    <path class="shape-from" fill="#000000" d="M21.062 21.062H78.94V78.94H21.06z"/> 
    <path class="shape-to" fill="#000000" d="M65.62 67.548l-44.558 11.39L32.858 37.41l46.08-16.348z"/> 
    <path class="shape-morph" fill="#000000" d="M21.062 21.062H78.94V78.94H21.06z"/> 
    </svg> 
</a> 

所以,當你將鼠標懸停在.link應該得到孩子.shape-morph,它以動畫的.shape-to值。然後在mouseleave上反轉。

$('.link').mouseenter(function() { 
    var shapeMorph = $(this).find('.shape-morph'); 
    var shapeTo = $(this).find('.shape-from').attr('d'); 
    anime({ 
    targets: shapeMorph, 
    d: shapeTo, 
    easing: 'easeOutElastic', 
    duration: 1000 
    }); 
}); 
$('.link').mouseleave(function() { 
    var shapeMorph = $(this).find('.shape-morph'); 
    var shapeFrom = $(this).find('.shape-from').attr('d'); 
    anime({ 
    targets: shapeMorph, 
    d: shapeFrom, 
    easing: 'easeOutElastic', 
    duration: 1000 
    }); 
}); 

我的另一個問題是,當它變形時偶爾會出現奇怪的閃爍,任何人都知道如何解決這個問題?

回答

0

我需要把的mouseenter /鼠標離開的each內,並通過功能發送正確的目標和路徑:JSFiddle

var path1 = 'M21.062 21.062H78.94V78.94H21.06z' 
var path2 = 'M35.062 21.062H60.94V78.94H21.06z' 

function animateMe(el, path) { 
    anime.remove(el); 
    anime({ 
    targets: el, 
    d: path, 
    easing: 'easeOutElastic', 
    duration: 1000 
    }); 
}; 

function enterLink(el, path) { 
    animateMe(el, path2); 
}; 

function leaveLink(el, path) { 
    animateMe(el, path1); 
}; 

$('.link').each(function() { 
    $(this).on('mouseenter', function(e) { 
    enterLink($(this).find('.shape-morph').get(0)); 
    }); 
    $(this).on('mouseleave', function(e) { 
    leaveLink($(this).find('.shape-morph').get(0)); 
    }); 
});