.net动态加载CSS样式表方法总结

方法一:利用Page类写入

<head>
<title>WebForm1</title>
<link  rel="stylesheet" type="text/css" href="" id="mycss">
</head>


 protected void Page_Load(object sender, EventArgs e)
{
   Page.RegisterStartupScript("css",@"<script>mycss.styleSheet.addImport('stylesheet1.css')</script>");
}

 

方法二:利用占位符 asp:placeholder

<head>
<title>WebForm1</title>
<asp:placeholder id="myplaceholder" runat="server"></asp:placeholder>
</head>

 protected void Page_Load(object sender, EventArgs e)
 {
     System.Web.UI.Control a = Page.FindControl("myplaceholder");
     System.Web.UI.HtmlControls.HtmlGenericControl objLink = new HtmlGenericControl("LINK");
     objLink.Attributes.Add("rel","stylesheet");
     objLink.Attributes.Add("type","text/css");
     objLink.Attributes.Add("href","StyleSheet1.css");
     objLink=objLink;
     a.Controls.Add(objLink);

 }

[注] asp:placeholder 这是控件是主要是起"占位符的做用"


方法三:转换为服务器控件

<head>
<title>WebForm1</title>
<link runat ="server" id="MyLink" href="StyleSheet1.css" rel="stylesheet" type="text/css" />
</head>

protected void Page_Load(object sender, EventArgs e)
{
    //动态更改css
    MyLink.Href = "";//css链接
}


方法四:利用asp:Literal

<head>
<title>WebForm1</title>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</head>

 protected void Page_Load(object sender, EventArgs e)
{
     //动态更改css
     Literal1.Text = "<link href='StyleSheet1.css' rel='stylesheet' type='text/css' />";
}

[住] asp:Literal可以将原句不变的输出

 

方法五:直接操作head内容

<head>
<title>WebForm1</title>
<link rel="stylesheet" type="text/css" href="" id="mycss">
</head>

 

 protected void Page_Load(object sender, EventArgs e)

{

            System.Web.UI.HtmlControls.HtmlGenericControl child = new System.Web.UI.HtmlControls.HtmlGenericControl("link");
            child.Attributes.Add("href", cssFilePath);
            child.Attributes.Add("rel", "stylesheet");
            child.Attributes.Add("type", "text/css");
            Page handler = (Page)HttpContext.Current.Handler;
            handler.Header.Controls.Clear();//清理
            handler.Header.Controls.Add(child);

}

posted @ 2011-08-29 09:05  Yao,Mane  阅读(584)  评论(0编辑  收藏  举报