【问题标题】:Any way to add a class to embedded SVG?有什么方法可以将类添加到嵌入式 SVG?
【发布时间】:2014-12-23 19:18:27
【问题描述】:

我正在构建一个顶部嵌入了 SVG 徽标的网站。它在绘制自己时有一个漂亮的动画。尽管在测试中,动画在每一页上都有动画,因此会分散注意力。我在 SVG 中添加了一个类,如果它有

 <svg class="showAnimation">

它动画,如果它没有那个类,它就不会动画。或者即使 showAnimation 类在任何父级上,也可以。但是做

<embed src="/media/logo.svg" class="showAnimation">

不起作用,因为我猜 HTML 中的类不会向下传播。我不想内联 SVG 文件并在每个页面上重新加载整个内容。

长话短说:我正在寻找一种在显示 SVG 之前从 HTML/CSS/Javascript 端向嵌入式 SVG 添加/删除类的有效方法。内联是低效的,因为它不能被缓存,使两个单独的 SVG 文件只有一个单词不同是低效的。

【问题讨论】:

    标签: html css svg


    【解决方案1】:

    您可以通过getSVGDocument() 获取embed 元素内的元素。

    var el = document.getElementById("embed's-id");
    el.addEventListener("load", function() {
      var svg = el.getSVGDocument().getElementById("your-svg's-id");
      svg.setAttribute('class', 'showAnimation');
    });
    

    如果load 事件没有触发,请尝试这样做。

    function checkIfLoaded() {
      var svg = document.getElementById("embed's-id").getSVGDocument();
      if (svg == null) {
        setTimeout(checkIfLoaded, 100);
      } else {
        svg.setAttribute('class', 'showAnimation');
      }
    }
    
    checkIfLoaded();
    

    【讨论】:

    • 知道为什么“加载”可能永远不会触发吗?该函数中的任何内容都没有运行。没有javascript错误,我做 var embedLogo = document.getElementById("embedLogo"); embedLogo.addEventListener("load", function() { alert("loaded");});并且永远不会收到警报。从 javascript 控制台我可以检查 embedLogo 是否定义正确。
    • @DanGoodspeed - 奇怪!它应该工作。也许尝试这样做this way
    • 嗯,这与我的上一个问题无关……但看起来 classList 不适用于 SVGDocument。 document.getElementById("embedLogo").classList 工作正常。 document.getElementById("embedLogo").getSVGDocument().classList 返回 undefined。
    • @DanGoodspeed - 我的错!你必须改用svg.setAttribute('class', 'showAnimation')
    • .setAttribute 也未为 SVGDocument 定义(再次仅适用于 HTML 元素)。
    猜你喜欢
    • 2014-07-30
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 2022-11-12
    相关资源
    最近更新 更多