我有這個 svg 代碼,它產生 3 個改變顏色的矩形。我想通過單擊這三個矩形中的任何一個來凍結它們,但我是 svg 的新手,我不知道該怎么做。我嘗試使用javascript,但它沒有用。有任何想法嗎?
<svg width="500" height="500" onclick="freezing()">
<rect x="10" y="20" width="90" height="60">
<animate id="a1" attributeName="fill" from="red" to="blue" dur="3s" fill="freeze" />
</rect>
<rect x="10" y="120" width="90" height="60">
<animate id="a2" attributeName="fill" from="blue" to="yellow" dur="3s" fill="freeze" />
</rect>
<rect x="10" y="220" width="90" height="60">
<animate id="a3" attributeName="fill" from="yellow" to="green" dur="3s" fill="freeze" />
</rect>
</svg>
uj5u.com熱心網友回復:
您可以使用SVGSVGElement#pauseAnimations方法暫停在此元素內運行的 SMIL 影片。要恢復它,您可以呼叫它unpauseAnimations()。
const svg = document.querySelector("svg");
svg.onclick = (evt) => {
if (svg.animationsPaused()) {
svg.unpauseAnimations();
}
else {
svg.pauseAnimations();
}
};
<svg width="500" height="500" >
<rect x="10" y="20" width="90" height="60">
<animate id="a1" attributeName="fill" from="red" to="blue" dur="3s" fill="freeze" />
</rect>
<rect x="10" y="120" width="90" height="60">
<animate id="a2" attributeName="fill" from="blue" to="yellow" dur="3s" fill="freeze" />
</rect>
<rect x="10" y="220" width="90" height="60">
<animate id="a3" attributeName="fill" from="yellow" to="green" dur="3s" fill="freeze" />
</rect>
</svg>
uj5u.com熱心網友回復:
將 SVG 中的 SMIL 影片與 JavaScript 結合起來確實很困難。在這里,我用JavaScript 中的影片物件替換了影片元素。影片物件有不同的方法,例如 play()、pause() 和 cancel()。
通過呼叫Element.getAnimations()您可以獲得元素上的所有影片。它是一個陣列,因此您需要遍歷它并暫停所有(在這種情況下只有一個)影片。
let timingoptions = {
duration: 3000,
fill: 'forwards'
};
document.querySelector('rect:nth-child(1)').animate([
{fill: 'red'},
{fill: 'blue'}
], timingoptions);
document.querySelector('rect:nth-child(2)').animate([
{fill: 'blue'},
{fill: 'yellow'}
], timingoptions);
document.querySelector('rect:nth-child(3)').animate([
{fill: 'yellow'},
{fill: 'green'}
], timingoptions);
document.querySelector('svg').addEventListener('click', e => {
e.target.getAnimations().forEach(animation => animation.pause());
});
<svg width="500" height="500">
<rect x="10" y="20" width="90" height="60"/>
<rect x="10" y="120" width="90" height="60"/>
<rect x="10" y="220" width="90" height="60"/>
</svg>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451867.html
標籤:javascript html svg
