cub*_*Guy 3 html javascript jquery svg
我正在尝试使用点击事件更改“xlink:href”属性,到目前为止它部分工作。这就是我正在做的
HTML:
<a href="#" class="ui-btn ui-corner-all ui-shadow editIcon" data-iconpos="top" data-transition="none" style="text-align:center">
<svg class="icon icon-pencil">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-pencil"> </use>
</svg>
</a>
Run Code Online (Sandbox Code Playgroud)
JS:
$('a.editIcon').on('click', function () {
if ($("a.editIcon svg").attr('class') == 'icon icon-pencil') {
$("a.editIcon svg").attr("class", "icon icon-floppy-disk");
$("a.editIcon svg use").attr("xlink:href", "#icon-floppy-disk");
} else {
myFunctionCall();
$("a.editIcon svg").attr("class", "icon icon-pencil");
$("a.editIcon svg use").attr("xlink:href", "#icon-pencil");
}
});
Run Code Online (Sandbox Code Playgroud)
发生的事情是我可以毫无问题地更改类,但是“xlink:href”属性没有改变,而是保留旧的(“#icon-pencil”),并添加了一个新的“ href" 属性(href="#icon-floppy-disk"):
<svg class="icon icon-floppy-disk">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-pencil" href="#icon-floppy-disk"></use>
</svg>
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么?谢谢!
我今天遇到了同样的问题,在四处搜索后,我找到了两个有效的解决方案。正如@Dr.Molle 和@prodigitalson 在这个问题的评论中所建议的那样,我能够使用:_HTMLNode_.setAttributeNS()来解决我的问题,但我不确定为什么这个解决方案对你不起作用@cubanGuy。
在深入研究 SVG Spec 之后,我了解到它xlink:href已被弃用,而赞成使用非命名空间href属性。该href属性(在 SVG 元素上)由一个 SVGAnimatedString 对象(用于反映可动画的字符串属性)表示,该对象具有两个属性:
interface SVGAnimatedString {
attribute DOMString baseVal;
readonly attribute DOMString animVal;
};
Run Code Online (Sandbox Code Playgroud)
这使我们能够href通过设置_HTMLNode_.href.baseVal更改xlink:href属性的值,这也会更改属性,因为 baseVal 设置器执行以下操作:
如果该
href属性不存在,则定义 SVGAnimatedString 对象以在已xlink:href弃用的属性存在时另外反映已弃用的属性。然后它将该弃用的属性设置为指定的值。
由于名称空间的属性是不鼓励,我建议_HTMLNode_.href.baseVal有利于被用来_HTMLNode_.setAttributeNS()支持现代浏览器的时候。如果您想查看它们的实际效果,我创建了一个片段来演示以下两种方法:
interface SVGAnimatedString {
attribute DOMString baseVal;
readonly attribute DOMString animVal;
};
Run Code Online (Sandbox Code Playgroud)
var svgElement1 = document.getElementById("editIcon1");
svgElement1.onclick = function () {
var useElement = this.getElementsByTagName("use")[0];
if (this.className === 'icon icon-locked') {
this.className = "icon icon-unlocked";
useElement.href.baseVal = "#unlocked";
} else {
this.className = "icon icon-locked";
useElement.href.baseVal = "#locked";
}
}
var svgElement2 = document.getElementById("editIcon2");
svgElement2.onclick = function () {
var useElement = this.getElementsByTagName("use")[0];
if (this.className === 'icon icon-locked') {
this.className = "icon icon-unlocked";
useElement.setAttributeNS('http://www.w3.org/1999/xlink', 'href', '#unlocked');
} else {
this.className = "icon icon-locked";
useElement.setAttributeNS('http://www.w3.org/1999/xlink', 'href', '#locked');
}
}Run Code Online (Sandbox Code Playgroud)
这是一个有效的 JSFiddle:https ://jsfiddle.net/ybtq9e03/
我希望这有帮助!