我是网络编程新手,需要一些帮助。我正在使用此 CSS 代码来动态控制标签的外观。如何从代码后面动态更改属性“width”的值?我还需要闪烁标签文本。请在下面找到我的代码
**strong text**
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.bar {
position: relative;
width: 250px;
height: 25px;
text-align: center;
line-height: 25px;
background: #003458;
background: linear-gradient(to bottom, #005478 0%,#003747 100%);
color: white;
}
.bar:before {
position: absolute;
display: block;
top: 0;
left: 0;
bottom: 0;
width: 40%;**** this value needs to be changed from code behind.
content: '';
background: rgba(0, 255, 0, 0.1);
}
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label18" runat= "server" CssClass="bar">20%</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
解决方案将不胜感激。
提前谢谢您!
最佳答案
您可以将该宽度
设置为您控制的变量:
.bar:before {
position: absolute;
display: block;
top: 0;
left: 0;
bottom: 0;
width: <%= BarWidth %>;
content: '';
background: rgba(0, 255, 0, 0.1);
}
然后在后面的代码中进行设置:
private string barWidth = "40%";
public string BarWidth
{
get { return barWidth; }
set { barWidth = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
barWidth="70%";
}
更新:根据您的评论...这是一种不同的方法。我将 .bar:before
重命名为 .barStatus
并从 CSS 中删除了 width
行。您不需要像我在示例中那样使用 HiddenField
...这只是一个示例,因此您可以观看它的工作原理,然后将其修复为您的代码所需的内容。
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="_bar" class="bar"><span id="_barStatus" style="width:0%;" class="barStatus" runat="server"></span></div>
<asp:Timer runat="server" id="Timer1" Interval="100" OnTick="UpdateBar"></asp:Timer>
<asp:HiddenField ID="_barState" Value="10" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
以及 OnTick 函数:
protected void UpdateBar(object sender, EventArgs e)
{
int barStatus = Convert.ToInt32(_barState.Value);
if (barStatus < 100)
{
barStatus += 2;
_barState.Value = barStatus.ToString();
_barStatus.Attributes["style"] = String.Format("width:{0}%;", barStatus);
_barStatus.InnerText = String.Format("{0}%", barStatus);
}
}
关于asp.net - 从代码隐藏更新 CSS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928126/