简体   繁体   English

没有在ASP.NET代码中动态设置CSS样式

[英]CSS Style not being set Dynamically in ASP.NET Code behind

I'm trying to change the CSS class and attributes of a set of asp.net controls via the code behind using this: 我试图通过使用此后面的代码来更改一组asp.net控件的CSS类和属性:

ASP.NET: ASP.NET:

<span id="followbtn_mainbtn" runat="server" class="follow-btner" onclick="profile_followers_follow(this)">

        <img id="img_followingbtn" runat="server" class="profile-single-profile-follow-btn-img" src="icons/profico/following.png" style="display: none;">
        <img id="img_unfollowbtn" runat="server" class="profile-single-profile-unfollow-btn-img" src="icons/profico/unfollow.png" style="display: none;">
        <img id="img_followicon" runat="server" class="profile-single-profile-follow-icon" src="icons/profico/followIcon.png">

        <span id="span_following_text" runat="server" class="profile-single-profile-follow-btn-following">Follow</span>
        <span id="span_unfollow_text" runat="server" class="profile-single-profile-follow-btn-unfollow" style="display: none;">Unfollow</span>

      </span>

Code: 码:

followbtn_mainbtn.Attributes.CssStyle.Add("className", "follow-btner-no-hoverer");
span_unfollow_text.InnerText = "Following";
img_followingbtn.Attributes.CssStyle.Add("display", "block");
img_unfollowbtn.Attributes.CssStyle.Add("display", "block");
span_unfollow_text.Attributes.CssStyle.Add("display", "block");

However when I run this, I do not see the desired results. 但是,当我运行此程序时,看不到预期的结果。 If I hard code the appropriate classes to the controls, they work properly but the code doesn't do it dynamically. 如果我将适当的类硬编码到控件中,则它们可以正常工作,但代码不会动态执行。

What am I doing wrong? 我究竟做错了什么?

Are you updating the css during a postback? 您是否在回发期间更新CSS? First try adding the changes to your Page_Load method on the form and that will tell you that your code is working when setting the styles and classes. 首先尝试将更改添加到窗体上的Page_Load方法,这将告诉您设置样式和类时代码正在工作。 If the code works then I would make sure you have EnableViewState="false" on your page and/or parent control of the span. 如果代码有效,那么我将确保您在页面上和/或跨度的父控件上具有EnableViewState =“ false”。

It was actually a simple error. 这实际上是一个简单的错误。 I've used the wrong code to change the css class of the span named "followbtn_mainbtn". 我使用了错误的代码来更改跨度的CSS类“ followbtn_mainbtn”。

I replaced this 我替换了这个

followbtn_mainbtn.Attributes.CssStyle.Add("className", "follow-btner-no-hoverer");

with this 有了这个

followbtn_mainbtn.Attributes["class"] = "follow-btner-no-hoverer";

Voila! 瞧! Done deal. 木已成舟。 Thanks for all your answers and comments though :) 谢谢您的所有回答和评论:)

您可以使用此代码在后面的代码中更改CSS

 img_followingbtn.Style.Add("display", "block");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM