使用JQuery,如何显示<div>,然后添加一些html,然后删除html然后隐藏div?

iHe*_*llo 3 javascript jquery timed

<div id="message" style="display: none">
 <!-- Here I want to place a message. It should be visible for 3 seconds.Then clear the      div to get ready for the next message. -->
</div>
Run Code Online (Sandbox Code Playgroud)

如何使用JQuery执行以下操作?

1.将消息插入div,其中id ="message"并使div可见.2.使消息可见3秒钟.3.删除div"message"的内容.4.隐藏div然后在必要时从步骤1开始.

先感谢您.

dan*_*lmb 9

我是这样做的:

$.msg = function(text, style)
{
    style = style || 'notice';           //<== default style if it's not set

    //create message and show it
    $('<div>')
      .attr('class', style)
      .html(text)
      .fadeIn('fast')
      .insertBefore($('#page-content'))  //<== wherever you want it to show
      .animate({opacity: 1.0}, 3000)     //<== wait 3 sec before fading out
      .fadeOut('slow', function()
      {
        $(this).remove();
      });
};
Run Code Online (Sandbox Code Playgroud)

例子:

$.msg('hello world');
$.msg('it worked','success');
$.msg('there was a problem','error');
Run Code Online (Sandbox Code Playgroud)

这个怎么运作

  1. 创建一个div元素
  2. 设置样式(这样你就可以改变外观)
  3. 设置要显示的html
  4. 消息开始消失,因此可见
  5. 将消息插入所需的位置
  6. 等了3秒
  7. 淡出信息
  8. 从DOM中删除div - 没有混乱!

奖金样本消息样式:

.notice, .success, .error {padding:0.8em;margin:0.77em 0.77em 0 0.77em;border-width:2px;border-style:solid;}
.notice {background-color:#FFF6BF;color:#514721;border-color:#FFD324;}
.success {background-color:#E6EFC2;color:#264409;border-color:#C6D880;}
.error {background-color:#FBE3E4;color:#8a1f11;border-color:#FBC2C4;}
.error a {color:#8a1f11;}
.notice a {color:#514721;}
.success a {color:#264409;}
Run Code Online (Sandbox Code Playgroud)

```


CMS*_*CMS 5

你可以这样做:

var $messageDiv = $('#message'); // get the reference of the div
$messageDiv.show().html('message here'); // show and set the message
setTimeout(function(){ $messageDiv.hide().html('');}, 3000); // 3 seconds later, hide
                                                             // and clear the message
Run Code Online (Sandbox Code Playgroud)