簡體   English   中英

在 c# 中動態改變 css 樣式?

[英]Dynamically changing css style in c#?

我有一些鏈接按鈕,我在其中動態添加樣式。 我在一種方法中執行以下操作:

LinkButton lb = new LinkButton();
lb.Style["font-weight"] = "bold";

單擊另一個鏈接時,它應該取消加粗的鏈接按鈕,並加粗當前單擊的鏈接按鈕,因此在執行此操作的方法中,我嘗試過:

lb.Style["font-weight"] = "none";

上面的方法不起作用,之前選擇的鏈接保持粗體。

我剛剛意識到可能的問題。 我正在創建多個鏈接,它看起來是因為所有鏈接都被命名為 lb,它永遠不會刪除粗體。 我正在想辦法讓它記住以前選擇的鏈接,並且只取消那個鏈接。

我可以建議一種替代方法嗎?

設置 CSS 樣式:

.selected { font-style: bold; }

單擊鏈接時,將該鏈接的 CSS class 設置為“已選擇”,其他設置為“”;

編輯:為了適應現有的 Css Class

const string MY_CLASS = "links";
lb1.CssClass = MY_CLASS + " selected"; // selected
lb.CssClass = MY_CLASS; // not selected

在定義內聯 styles 時,您很快就會遇到麻煩,因為它們很難被覆蓋。

編輯2:

像這樣的代碼應該可以工作。 您可能必須遍歷列表中的所有 LinkButton,但我不這么認為。 我只是關閉 LinkButtons 上的 ViewState。

// container for links. so you can reference them 
// outside of the creation method if you wish. I'd probably call this method in the  
// Page_Init Event.

List<LinkButton> listOfLinks = new List<LinkButton>();
const string MY_LB_CLASS = "linkButton"; // generic lb class


private void createSomeLinks() {

    for (int i = 0; i < 10; i++) {
        // create 10 links.
        LinkButton lb = new LinkButton() 
        { 
            ID = "lb" + i, 
            CssClass = MY_LB_CLASS 
        };
        lb.Click += new EventHandler(lb_Click); // Add the click event
    }

    // You can bind the List of LinkButtons here, or do something with them.
}

void lb_Click(Object sender, EventArgs e) {

    LinkButton lb = sender as LinkButton; // cast the sender as LinkButton
    if (lb != null) {
        // Make the link you clicked selected.
        lb.CssClass = MY_LB_CLASS + " selected"; 
    }
}

試試 lb.Style.Remove("font-weight")。 我沒有測試它,但你可以試試。

或者,您是否嘗試過設置 Font.Bold 屬性?

lb.Font.Bold = true;

試試ListBox1.Attributes.Add("style","font-weight:bold"); ListBox1.Attributes.Add("style","font-weight:normal");

甚至更好的是

// css

.active {font-weight:bold}
.notactive {font-weight:normal}

//C#

ListBox1.CssClass = "active";
ListBox1.CssClass = "notactive ";

你可以試試 lb.Style.Remove("font-weight");

在鏈接按鈕的單擊事件中設置粗體字體,並在單擊事件本身中將啟用視圖 state 屬性設置為 false,這將在其他單擊中將鏈接重置為正常泡沫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM