如何使用jquery向用户显示弹出式通知?

21

我正在开发一个应用程序,需要通知用户一些后台事件,比如其他用户的邀请、提醒超时等。

每当事件发生时,控制器将被通知,并应该显示一个小窗口给用户。

我应该怎么做才能实现这个功能。哪种技术/工具可以帮助我。我正在使用jQuery,JSF 2.0和Spring 3.0。

4个回答

29

这将会给出一个类似于stackoverflow的通知。

jQuery

$("#notification").fadeIn("slow").append('your message');
$(".dismiss").click(function(){
       $("#notification").fadeOut("slow");
});

HTML

<div id="notification" style="display: none;">
  <span class="dismiss"><a title="dismiss this notification">x</a></span>
</div>

CSS

#notification {
    position:fixed;
    top:0px;
    width:100%;
    z-index:105;
    text-align:center;
    font-weight:normal;
    font-size:14px;
    font-weight:bold;
    color:white;
    background-color:#FF7800;
    padding:5px;
}
#notification span.dismiss {
    border:2px solid #FFF;
    padding:0 5px;
    cursor:pointer;
    float:right;
    margin-right:10px;
}
#notification a {
    color:white;
    text-decoration:none;
    font-weight:bold
}

还要看一下mplungjan的回答,了解如何监听服务器更新和消息加载


@mplungjan,太好了,但现在我注意到OP也要求服务器端的帮助。 - Anupam
所以脚本需要轮询服务器。没问题。setInterval和$.get()。 - mplungjan
是的,我会更新我的答案。顺便问一下,有没有其他逻辑可以触发事件,而不使用 setInterval() 实现呢? - Anupam
长轮询(Long poll)或彗星(Comet) - mplungjan

2

使用来自@Anu建议-我的示例。的代码,您可���简单地添加一个投票。

$(document).ready(function() {
  $(".dismiss").click(function(){$("#notification").fadeOut("slow");});

  setInterval(function() {
    $.get("ping.jsp?userid=<%= userID %>",function(message) {
      if (message) $("#notification").fadeIn("slow").html(message);
    });
   ,10000);
})

如果不需要通知,则可以在消息中包含时间戳以查看之前是否已经发送了通知,而不是发送空消息。

可选方案:长轮询Comet


2

HTML:

<input type="button" id="pop" value="Submit"/>
<div id="popup">
  <div id="topbar"> TITLE..</div>
  <div id="content">Here is you content...</div>
  <input type="button" id="ok" value="OK"/>
</div>

CSS:

#popup { background:#ccc; -moz-border-radius: 10px; width:300px; height: 200px; padding: 5px; position: absolute; left: 50%; margin-left: -150px; z-index: 500; display:none }
#topbar { background:#ddd; -moz-border-radius: 10px; padding:5px; height:20px; line-height:20px }
#content { padding:5px; -moz-border-radius: 10px; text-align:center }
#ok { position: absolute; left: 140px; top: 180px }

JQUERY:

$(function(){
    $('#pop').click(function(){
        $('#popup').fadeIn().css('top',$(document).height()/2);
    });
    $('#ok').click(function(){
        $('#popup').fadeOut();
    });
});

1
修复了 CSS ID 弹出窗口 - 添加了一个 fiddle,减去弹出窗口的高度也是一个好主意。 - mplungjan

1

Jquery ui对话框是您正在寻找的。它会为您提供很大的帮助。虽然还有许多其他插件可用,但这是最简单的。


实际上,看了其他的例子,这里根本不需要jQuery UI。 - mplungjan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接