Я думаю, что могут быть некоторые методы CSS, чтобы сделать этот код проще и короче, но чтобы сделать ваш код совместимым со всеми браузерами, я следую за тем, как вы это делаете.
Вам необходимо передать новое сообщение вашей функции JS. Я также изменил JS для передачи идентификатора элемента управления, чтобы вы могли использовать код для нескольких элементов на своей странице.
<script type="text/javascript">
function toHex(d) {
return ("0" + (Number(d).toString(16))).slice(-2).toUpperCase()
}
var direction = 1;
var timer_is_on = 0;
var rgb = 0;
function timedCount(controlId, newMsg) {
var lab = document.getElementById(controlId);
if (direction == 1) {
rgb = rgb + 15;
}
if (direction == -1) {
rgb = rgb - 15;
}
lab.style.color = "#" + toHex(rgb) + toHex(rgb) + toHex(rgb);
if (rgb >= 255 || rgb <= 0) {
if (direction == 1) {
direction = -1;
lab.innerText = newMsg;
}
else {
timer_is_on = 0;
return;
}
}
setTimeout(timedCount.bind(null, controlId, newMsg), 50);
}
function startEffect(controlId, newMsg) {
if (!timer_is_on) {
timer_is_on = 1;
direction = 1;
rgb = 0;
timedCount(controlId, newMsg);
}
}
</script>
Также, чтобы решить проблему с постбэк, вам нужно использовать скрытое поле, чтобы сделать трюк. Это важно, иначе ваш текст будет восстановлен после постбека.
<form id="frm" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="pnlMain" runat="server">
<ContentTemplate>
<asp:HiddenField ID="hfMessage" runat="server" />
<div style="width: 400px; margin: 0 auto; text-align: center; font-size: x-large">
<asp:Label ID="lblMessage" runat="server" Text="No Record is Selected"></asp:Label>
</div>
<asp:Button ID="btnFlash" runat="server" Text="Change Text" OnClick="btnFlash_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
А это код позади
protected void Page_Load(object sender, EventArgs e)
{
// on first load, store the text message in hidden field
if (!Page.IsPostBack)
{
hfMessage.Value = lblMessage.Text;
}
if (Page.IsPostBack)
{
// on postback, set the text message from hidden field which is populated in button click
lblMessage.Text = hfMessage.Value;
}
}
protected void btnFlash_Click(object sender, EventArgs e)
{
// This would be your message, I just used a date-time to create dynamic message.
string newMessage = DateTime.Now.Second.ToString() + " Records Selected";
// store the new message in hidden field to change the text on post-back, otherwise your message will be restored on post-back
hfMessage.Value = newMessage;
// call JS from code-behind, pass the control ID and the new message
ScriptManager.RegisterStartupScript(this, GetType(), "flash", "startEffect('lblMessage', '" + newMessage + "');", true);
}
Это был сложный вопрос:)