Исчезать (мигать) текст с помощью JavaScript в приложении C # ASP.Net - PullRequest
0 голосов
/ 24 июня 2018

В части моего приложения (WebForm ASP.Net) я изменяю текст на веб-странице.Чтобы привлечь внимание пользователя к изменению, я хочу постепенно затенить текст, пока он полностью не исчезнет, ​​затем изменить текст, а затем постепенно показать новый текст.

Я частично реализовал это в JavaScript,Я могу постепенно увеличивать и уменьшать текст, используя следующие коды:

JavaScript

<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() {
        var lab = document.getElementById('lblMessage');
        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;
            }
            else {
                timer_is_on = 0;
                return;
            }
        }
        setTimeout(timedCount, 50);
    }

    function startEffect() {
        if (!timer_is_on) {
            timer_is_on = 1;
            direction = 1;
            rgb = 0;
            timedCount();
        }
    }
</script>

ASPX

<form id="frm" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="pnlMain" runat="server">
        <ContentTemplate>
            <div style="width: 400px; margin: 0 auto; text-align: center; font-size: x-large">
                <span id="lblMessage">No Record is Selected</span>
            </div>
            <button onclick="startEffect()">Start!</button>
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

Проблема

Я не знаю 2 вещей:

  1. Как изменить текст после завершения затухания
  2. Как сделать все это из кода в C #.

Примечание. Я хочу сделать это без jQuery или любой другой библиотеки JavaScript.

1 Ответ

0 голосов
/ 24 июня 2018

Я думаю, что могут быть некоторые методы 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);
}

Это был сложный вопрос:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...