【问题标题】:Change the width of a svg with an animation用动画改变 svg 的宽度
【发布时间】:2014-07-17 21:50:15
【问题描述】:

我在这个对象中有一个svg 图像:

<object id="firstrule" type="image/svg+xml" data="/assets/rules/pertinance.svg"></object>

我想让它出现在带有动画的滚动条上。我已经为滚动编写了良好的回调,现在我对如何制作动画感到困惑。

动画将是:开始时,svg 的宽度为 0,当触发回调时,svg 现在采用其正常大小的 100%。动画应该需要 3 秒,在这 3 秒内,我们可以看到图像的大小从 0 变为 100%。

为此,我尝试了以下方法: 1) 将我的对象“firstrule”的宽度属性设置为 0%

<object id="firstrule" type="image/svg+xml" data="/assets/rules/pertinance.svg" width="0%"></object>

以及 2) 使用 jquery 触发动画

$('#firstrule').animate({'width':'100%'},3000);

它不起作用,我在浏览器的控制台上收到此错误:TypeError: Cannot set property 'cur' of undefined

您是否知道另一种解决方案(可能使用 CSS3?),或者如何解决这个问题?我想要一个简单的解决方案,不要打扰很多行,也不要使用任何插件。我很确定可以轻松克服这个问题。

【问题讨论】:

    标签: javascript jquery css svg


    【解决方案1】:

    简单的解决方法:将带有 SVG 图像的 &lt;object&gt; 放在包装 &lt;div&gt; 中。然后为容器而不是对象设置动画。

    <style>
        #wrapper { width: 0; }
        #firstrule { width: 100%; height: 100%; }
    </style>
    
    <div id="wrapper">
        <object id="firstrule" 
            type="image/svg+xml" 
            data="/assets/rules/pertinance.svg">
        </object>
    </div>
    
    <script>
        function animate() {
            $("#wrapper").animate({ width: "100%" }, 3000);
        }
    </script>
    


    JSFiddle

    【讨论】:

    • 正是我想要的!在这之间,你介意解释一下为什么我们应该将 svg 设置在包装器中吗?
    • 包装器是必要的,因为显然不可能用 jQuery 直接为 &lt;object&gt; 元素设置动画。但是,即使我检查了 jQuery 源代码中的相关部分,我也无法向您解释为什么会这样......
    • 确实,这是不可能的,但是通过使用纯 js (setInterval) 的 Hristo Georgiev 解决方案是可能的。很奇怪
    【解决方案2】:

    如果你想直接与对象交互,你总是可以依靠好的 ol' javascript:

    变量 i = 0;

    变量重复

    function animate() {
    
    
        repeat = setInterval(function () {
            add();
        }, 1);
    
        function add() {
            document.getElementById("firstrule").style.width = i + '%';
            document.getElementById("firstrule").style.height = i + '%';
            i++;
            if (i >= 100) {
                clearInterval(repeat);
            }
        }
    
    
    }
    

    JSFIDDLE

    【讨论】:

    • 这是迄今为止最巧妙的解决方案,谢谢。但是动画在三秒钟后并没有停止,我需要更简单的东西,所以我选择了 Aletheios 答案;)
    猜你喜欢
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2022-11-01
    相关资源
    最近更新 更多