发生这种情况是因为 SVG DOM 规范与 HTML DOM 有很大不同。
SVG DOM 是一种不同的方言,有些属性具有相同的名称但含义不同。例如,要获取 svg 元素的 className,请使用:
svg.className.baseVal
受此影响的属性是
className is SVGAnimatedString
height,width, x, y, offsetWidth, offsetHeight are SVGAnimatedLength
这些 Animated 属性是结构,具有与baseVal
您在 HTML DOM 中找到的相同的值,但animatedVal
我不确定是什么。
SVG DOM 也缺少一些依赖的属性库,例如innerHTML
.
这在很多方面破坏了 jQuery,任何依赖于上述属性的东西都会失败。
一般来说,SVG DOM 和 HTML DOM 不能很好地混合。他们一起工作足以引诱你进入,然后事情悄悄地破裂,另一个天使失去了翅膀。
我写了一个小的 jQuery 扩展来包装 SVG 元素,使它们看起来更像 HTML DOM
(function (jQuery){
function svgWrapper(el) {
this._svgEl = el;
this.__proto__ = el;
Object.defineProperty(this, "className", {
get: function(){ return this._svgEl.className.baseVal; },
set: function(value){ this._svgEl.className.baseVal = value; }
});
Object.defineProperty(this, "width", {
get: function(){ return this._svgEl.width.baseVal.value; },
set: function(value){ this._svgEl.width.baseVal.value = value; }
});
Object.defineProperty(this, "height", {
get: function(){ return this._svgEl.height.baseVal.value; },
set: function(value){ this._svgEl.height.baseVal.value = value; }
});
Object.defineProperty(this, "x", {
get: function(){ return this._svgEl.x.baseVal.value; },
set: function(value){ this._svgEl.x.baseVal.value = value; }
});
Object.defineProperty(this, "y", {
get: function(){ return this._svgEl.y.baseVal.value; },
set: function(value){ this._svgEl.y.baseVal.value = value; }
});
Object.defineProperty(this, "offsetWidth", {
get: function(){ return this._svgEl.width.baseVal.value; },
set: function(value){ this._svgEl.width.baseVal.value = value; }
});
Object.defineProperty(this, "offsetHeight", {
get: function(){ return this._svgEl.height.baseVal.value; },
set: function(value){ this._svgEl.height.baseVal.value = value; }
});
};
jQuery.fn.wrapSvg = function() {
return this.map(function(i, el) {
if (el.namespaceURI == "http://www.w3.org/2000/svg" && !('_svgEl' in el))
return new svgWrapper(el);
else
return el;
});
};
})(window.jQuery);
它为 SVG 对象创建了一个包装器,使它们看起来像 jQuery 的 HTML DOM。我已经将它与 jQuery-UI 一起使用,使我的 SVG 元素可放置。
HTML 和 SVG 之间缺乏 DOM 互操作性是一场彻头彻尾的灾难。所有为 HTML 编写的甜蜜实用程序库都必须为 SVG 重新发明。