我正试图 svg 通过使用 use 元素如下所示:
svg
use
<svg class="xyz" width="25px" height="25px" fill="red" xmlns:xlink="http://www.w3.org/1999/xlink"> <use id="useLogo" runat=server class="xyz" href="~/Content/images/test.svg#shape" xlink:href="~/Content/images/test.svg#shape"></use> </svg>
问题是我在用户控件中执行此操作,因此我需要引用 svg 相对于应用程序的文件,而不是用户控件所在的页面。
我决定使用 ~ 中的字符 href 和 xlink:href 属性,然后启用 page_load :
~
href
xlink:href
page_load
protected void Page_Load(object sender, EventArgs e) { this.useLogo.Attributes["href"] = Page.ResolveUrl(this.useLogo.Attributes["href"]); //this.useLogo.Attributes["xlink:href"] = Page.ResolveUrl(this.useLogo.Attributes["xlink:href"]); }
这确实有效,但为了向后兼容,我需要对 xlink:href 属性该名称空间似乎正在绊倒ASP。Net作为 AttributeCollection 元素的“”没有该属性的项。是否有某种方法可以识别名称空间属性,或者有完全不同的方法可以做到这一点?
AttributeCollection
如果在浏览器中运行应用程序并查看源代码,则会注意到 xlink:href 已剥离,您的控件呈现为:
<use id="MainContent_useLogo" class="xyz" href="~/Content/images/test.svg#shape"></use>
请注意 runat 属性也丢失。所有这些都是ASP引擎处理标记的结果,它决定如何处理每个属性。
runat
因为这两个属性被剥离,所以 Attributes 属性不包括它们,它只包括 class 和 href 在你的情况下。
Attributes
class
既然你想要 href 和 xlink:href 属性具有相同的值,只需添加 xlink:href 属性,并将其设置为 href 属性:
useLogo.Attributes["href"] = ResolveUrl(this.useLogo.Attributes["href"]); useLogo.Attributes.Add("xlink:href", useLogo.Attributes["href"]);