ASP.NET中直接用C# 動態(tài)修改CSS樣式 wonsoft (wonsoft@163.com)
使用JavaScript控制CSS樣式有點麻煩,還是覺得直接使用C#操作更方便快捷,本文通過兩個Button控制TextBox1的高度和背景色,以展示通過C#控制CSS樣式的方法。以下是操作的實例:
一、前端代碼(TestEditStyle.aspx.)如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestEditStyle.aspx.cs" Inherits="Test_TestEditStyle" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www./1999/xhtml">
<head runat="server">
<title>無標題頁</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
二、后臺代碼(TestEditStyle.aspx.cs)如下:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Test_TestEditStyle : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Style["background-color"] = "blue"; //背景設(shè)為藍色
TextBox1.Style["height"] = "200px"; //高度設(shè)為200
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Style["background-color"] = "red"; //背景設(shè)為紅色
TextBox1.Style["height"] = "100px"; //高度設(shè)為100
}
}
三、補充說明:
只要在標簽里加上runat ="server"和ID="MyTag",就可在后臺代碼中直接通過設(shè)置MyTag.Style的值來控制樣式?! ±纾?/font>
在前端加入:
<div id="mydiv" runat="server"></div>
后臺即可以直引用mydiv這個對像進行控制:
mydiv.Style["width"] = "100px";
mydiv.Style["height"] = "100px";
mydiv.Style["background-color"] = "yellow";
(以上代碼在VS2008上調(diào)試通過)
wonsoft
2008/6/14于成都
|
|
來自: goodwangLib > 《C#》