【问题标题】:adding image namespace in svg through JS still doesn't show me the picture通过 JS 在 svg 中添加图像命名空间仍然没有显示图片
【发布时间】:2011-10-17 03:05:02
【问题描述】:

在通过图片的缩放版本获取参数后,我正在尝试通过 Javascript 在 SVG 中添加带有原始尺寸参数的图片。

Firebug 向我展示了元素和所有必要的参数,但最好的祝愿是我没有通过。

this.svg = document.getElementsByTagNameNS('http://www.w3.org/2000/svg','svg');     
var bild = document.createElementNS('http://www.w3.org/2000/svg','image');
var BildURL = this.image[0][0].getAttribute('xlink:href');
var imgX = new Image();
imgX.src = BildURL;

bild.setAttribute("x","60");
bild.setAttribute("y","40");
bild.setAttribute("width",imgX.width);
bild.setAttribute("height",imgX.height);    
bild.setAttribute("id","image12976");
bild.setAttribute("xlink:href",BildURL);
this.svg[0].appendChild(bild);

如果我查看 Firebug,该元素完全存在。

<image id="image12976" x="60" y="40" width="300" height="430" xlink:href="img/Akira1.jpg">

我将鼠标移到屏幕上,在“投资模式”中看到图片的矩形,但看不到内容。

谁能告诉我我做错了什么?!

非常感谢您。

驯服者

【问题讨论】:

    标签: javascript dom svg client-side client-side-scripting


    【解决方案1】:

    尝试使用null 命名空间创建图像:

    var bild = document.createElementNS(null, 'image');
    

    【讨论】:

      【解决方案2】:

      您永远不应该对具有前缀的属性使用 getAttribute/setAttribute,有关原因的更多详细信息,请参阅DOM 3 Core。

      如果你使用它会工作得很好

      getAttributeNS('http://www.w3.org/1999/xlink', 'href')

      和

      setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', your_url_here).

      【讨论】:

      • 就是这样...... !!!昨天我也想通了。不过非常感谢!
      • 错了。 getAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href') 不起作用。 getAttribute("xlink:href") 有效。 developer.mozilla.org/en-US/docs/DOM/…
      • @Green:请举个例子。不建议将命名空间属性与非命名空间感知的 DOM 方法混合使用。
      • @ErikDahlström,请看我的问题stackoverflow.com/questions/12422668/…
      • 这是 DOM 陷阱之一,在 getAttributeNS 中,属性不能有前缀 (xlink:href),但在 setAttributeNS 中应该(用于序列化)。我已经更新了答案(它适用于包括 chrome 在内的所有浏览器,请参阅w3.org/TR/DOM-Level-3-Core/core.html#ID-ElGetAttrNS。
      猜你喜欢
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 2014-01-02
      相关资源
      最近更新 更多