通知面板类似于stackoverflow

时间:2008-12-14 19:10:03

标签: asp.net-mvc

请记住页面顶部显示的小div,以便通知我们(例如新徽章)?

我也想实现类似的东西,并且正在寻找一些最佳实践或模式。

我的网站也是一个ASP.NET MVC应用程序。理想情况下,答案将包括诸如“在主页面中放置”和“在控制器中执行”等细节。

为了让您不必自己看,这是我在未在stackoverflow登录时收到的欢迎消息中看到的代码。

<div class="notify" style="">
  <span>
    First time at Stack Overflow? Check out the
    <a href="/messages/mark-as-read?returnurl=%2ffaq">FAQ</a>!
  </span>
  <a class="close-notify" onclick="notify.close(true)" title="dismiss this notification">×</a>
</div>

<script type="text/javascript">

  $().ready(function() {
    notify.show();
  });

</script>

我想补充一点,我完全理解这一点,也理解jquery的参与。我只是对将代码放入标记以及何时(“谁”和ASP.NET MVC应用程序中的哪些实体)感兴趣。

谢谢!

6 个答案:

答案 0 :(得分:12)

This answer有完整的解决方案。

复制粘贴:

这是标记,最初是隐藏的,所以我们可以淡化它:

<div id='message' style="display: none;">
    <span>Hey, This is my Message.</span>
    <a href="#" class="close-notify">X</a>
</div>

以下是应用的样式:

#message {
    font-family:Arial,Helvetica,sans-serif;
    position:fixed;
    top:0px;
    left:0px;
    width:100%;
    z-index:105;
    text-align:center;
    font-weight:bold;
    font-size:100%;
    color:white;
    padding:10px 0px 10px 0px;
    background-color:#8E1609;
}

#message span {
    text-align: center;
    width: 95%;
    float:left;
}

.close-notify {
    white-space: nowrap;
    float:right;
    margin-right:10px;
    color:#fff;
    text-decoration:none;
    border:2px #fff solid;
    padding-left:3px;
    padding-right:3px
}

.close-notify a {
    color: #fff;
}

这是javascript(使用jQuery):

$(document).ready(function() {
    $("#message").fadeIn("slow");
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
        return false;
    });
});

瞧。根据您的页面设置,您可能还需要在显示屏上编辑正文边距。

Here is a demo of it in action

答案 1 :(得分:11)

稍微窥探一下代码后,这是一个猜测:

以下通知容器始终位于视图标记中:

<div id="notify-container"> </div>

默认情况下隐藏了通知容器,并且在某些情况下由javascript填充。它可以包含任意数量的消息。

如果用户未登录

持久性:Cookie用于跟踪是否显示消息。

视图中的服务器端生成的代码: 我认为如果您没有登录,stackoverflow只会显示一条消息。以下代码将注入视图中:

<script type="text/javascript">
    $(function() { notify.showFirstTime(); });
</script>

showFirstTime()javascript方法只决定是否显示“这是你第一次来这里吗?”基于cookie是否已设置的消息。如果没有cookie,则显示该消息。如果用户采取了操作,则会设置cookie,并且将来不会显示该消息。 nofity.showFirstTime()函数处理cookie的检查。

如果用户已登录

持久性:数据库用于跟踪消息是否已显示。

视图中的服务器端生成的代码: 当请求页面时,服务器端代码检查数据库以查看需要显示哪些消息。然后,服务器端代码以json格式将消息注入视图,并向showMessages()发出javascript调用。

例如,如果我登录到视图,我会在标记处看到以下内容:

    <script type="text/javascript">
1
2 var msgArray = [{"id":49611,"messageTypeId":8,"text":"Welcome to Super User! Visit your \u003ca href=\"/users/00000?tab=accounts\"\u003eaccounts tab\u003c/a\u003e to associate with our other websites!","userId":00000,"showProfile":false}];
3 $(function() { notify.showMessages(msgArray); });
4
</script>

因此,如果用户未登录,则服务器端代码会注入代码以调用“showFirstTime”方法,或者为注册用户注入消息并调用“showMessages”。

有关客户端代码的更多信息

另一个关键组件是Picflight已经缩小的“通知”JavaScript模块(你可以使用yslow为firebug做同样的事情)。通知模块基于服务器端生成的javascript处理通知div的填充。

未登录,客户端

如果用户未登录,则模块会在用户X发出通知时处理事件,或通过创建cookie转到FAQ。它还通过检查cookie来确定是否显示第一次消息。

已登录,客户端

如果用户已登录,则通知模块会将服务器生成的所有消息添加到通知div中。当用户解除消息时,它也很可能使用ajax来更新数据库。

答案 2 :(得分:4)

虽然这些并不是官方的,但我遵循的常见做法会产生这样的结果:

  • 创建将在标记中充当通知容器的元素,但默认情况下隐藏它(这可以通过多种方式完成 - JavaScript,外部CSS或内联样式)。
  • 让脚本负责通知在标记之外的行为。在上面的示例中,您可以看到有一个onclick以及另一个在标记中包含的页面加载时触发的函数。虽然它有效,但我将其视为混合演示和行为。
  • 将通知消息的演示文稿保存在外部样式表中。

同样,这些只是我在您的问题中陈述的常见做法。正如你的问题的本质已经表明的那样,网络开发的事情是有很多方法可以用相同的结果做同样的事情。

答案 3 :(得分:4)

我看到以下jQuery函数?我相信,使用id notify-container将html注入到div中。

我不明白如何根据某些事件使用和调用此JS,也许有人可以解释。

var notify = function() {
var d = false;
var e = 0;
var c = -1;
var f = "m";
var a = function(h) {
    if (!d) {
        $("#notify-container").append('<table id="notify-table"></table>');
        d = true
    }
    var g = "<tr" + (h.messageTypeId ? ' id="notify-' + h.messageTypeId + '"' : "");
    g += ' class="notify" style="display:none"><td class="notify">' + h.text;
    if (h.showProfile) {
        var i = escape("/users/" + h.userId);
        g += ' See your <a href="/messages/mark-as-read?messagetypeid=' + h.messageTypeId + "&returnurl=" + i + '">profile</a>.'
    }
    g += '</td><td class="notify-close"><a title="dismiss this notification" onclick="notify.close(';
    g += (h.messageTypeId ? h.messageTypeId : "") + ')">&times;</a></td></tr>';
    $("#notify-table").append(g)
};
var b = function() {
    $.cookie("m", "-1", {
        expires: 90,
        path: "/"
    })
};
return {
    showFirstTime: function() {
        if ($.cookie("new")) {
            $.cookie("new", "0", {
                expires: -1,
                path: "/"
            });
            b()
        }
        if ($.cookie("m")) {
            return
        }
        $("body").css("margin-top", "2.5em");
        a({
            messageTypeId: c,
            text: 'First time here? Check out the <a onclick="notify.closeFirstTime()">FAQ</a>!'
        });
        $(".notify").fadeIn("slow")
    },
    showMessages: function(g) {
        for (var h = 0; h < g.length; h++) {
            a(g[h])
        }
        $(".notify").fadeIn("slow");
        e = g.length
    },
    show: function(g) {
        $("body").css("margin-top", "2.5em");
        a({
            text: g
        });
        $(".notify").fadeIn("slow")
    },
    close: function(g) {
        var i;
        var h = 0;
        if (g && g != c) {
            $.post("/messages/mark-as-read", {
                messagetypeid: g
            });
            i = $("#notify-" + g);
            if (e > 1) {
                h = parseInt($("body").css("margin-top").match(/\d+/));
                h = h - (h / e)
            }
        } else {
            if (g && g == c) {
                b()
            }
            i = $(".notify")
        }
        i.children("td").css("border-bottom", "none").end().fadeOut("fast", function() {
            $("body").css("margin-top", h + "px");
            i.remove()
        })
    },
    closeFirstTime: function() {
        b();
        document.location = "/faq"
    }
 }
} ();

答案 4 :(得分:2)

StackOverflow使用jQuery - 你从SO发布的JS代码是一个jQuery调用。几乎没有代码,它会完全符合您的要求。强烈推荐。

答案 5 :(得分:0)

我写了这篇Javascript就是这样做的,包括堆叠,当你像Stack Overflow一样滚动时和你在一起,并且每当添加一个新栏时都会向下推动整个页面。酒吧也到期了。酒吧也滑落了。

// Show a message bar at the top of the screen to tell the user that something is going on.
// hideAfterMS - Optional argument. When supplied it hides the bar after a set number of milliseconds.
    function AdvancedMessageBar(hideAfterMS) {
        // Add an element to the top of the page to hold all of these bars.
        if ($('#barNotificationContainer').length == 0) 
        {               

        var barContainer = $('<div id="barNotificationContainer" style="width: 100%; margin: 0px; padding: 0px;"></div>');
        barContainer.prependTo('body');

        var barContainerFixed = $('<div id="barNotificationContainerFixed" style="width: 100%; position: fixed; top: 0; left: 0;"></div>');
        barContainerFixed.prependTo('body');
    }

    this.barTopOfPage = $('<div style="margin: 0px; background: orange; width: 100%; text-align: center; display: none; font-size: 15px; font-weight: bold; border-bottom-style: solid; border-bottom-color: darkorange;"><table style="width: 100%; padding: 5px;" cellpadding="0" cellspacing="0"><tr><td style="width: 20%; font-size: 10px; font-weight: normal;" class="leftMessage" ></td><td style="width: 60%; text-align: center;" class="messageCell"></td><td class="rightMessage" style="width: 20%; font-size: 10px; font-weight: normal;"></td></tr></table></div>');
    this.barTopOfScreen = this.barTopOfPage.clone();

    this.barTopOfPage.css("background", "transparent");
    this.barTopOfPage.css("border-bottom-color", "transparent");
    this.barTopOfPage.css("color", "transparent");

    this.barTopOfPage.prependTo('#barNotificationContainer');
    this.barTopOfScreen.appendTo('#barNotificationContainerFixed');


    this.setBarColor = function (backgroundColor, borderColor) {     

        this.barTopOfScreen.css("background", backgroundColor);
        this.barTopOfScreen.css("border-bottom-color", borderColor);
    };

    // Sets the message in the center of the screen.
    // leftMesage - optional
    // rightMessage - optional
    this.setMessage = function (message, leftMessage, rightMessage) {
        this.barTopOfPage.find('.messageCell').html(message);
        this.barTopOfPage.find('.leftMessage').html(leftMessage);
        this.barTopOfPage.find('.rightMessage').html(rightMessage);

        this.barTopOfScreen.find('.messageCell').html(message);
        this.barTopOfScreen.find('.leftMessage').html(leftMessage);
        this.barTopOfScreen.find('.rightMessage').html(rightMessage);
    };


    this.show = function() {
        this.barTopOfPage.slideDown(1000);
        this.barTopOfScreen.slideDown(1000);
    };

    this.hide = function () {
        this.barTopOfPage.slideUp(1000);
        this.barTopOfScreen.slideUp(1000);
    };

    var self = this;   


    if (hideAfterMS != undefined) {
        setTimeout(function () { self.hide(); }, hideAfterMS);
    }    
}

要使用它,您必须使用jQuery并确保页面正文没有边距或填充。

AdvancedMessageBar采用的参数是可选的。如果提供,它将导致条在一定时间后以毫秒消失。

var mBar = new AdvancedMessageBar(10000);
mBar.setMessage('This is my message', 'Left Message', 'Right Message');
mBar.show();

如果你想堆叠它们,那么只需创建更多的AdvancedMessageBar对象,它们就会自动堆叠。