簡體   English   中英

使用JQuery,我該如何制作一個 <div> 出現,然后添加一些HTML,然后刪除html然后隱藏div?

[英]Using JQuery, how can I make a <div> appear, then add some html, then remove the html and then hide the div?

<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>

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

1.將消息插入div,其中id =“message”並使div可見。 2.使消息可見3秒鍾。 3.刪除div“message”的內容。 4.隱藏div然后在必要時從步驟1開始。

先感謝您。

我是這樣做的:

$.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();
      });
};

例子:

$.msg('hello world');
$.msg('it worked','success');
$.msg('there was a problem','error');

這個怎么運作

  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;}

```

你可以這樣做:

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

這是一個小腳本,以3秒的間隔循環顯示消息。 也許這不是你需要的,但我希望它可以幫助你實現你想要的。

var messages = [
  "test message 0",
  "test message 1",
  "test message 2",
  "test message 3"
];

$(function() {
  var msgIndex = 0;
  setInterval(function() {
    $msgDiv = $("#message");
    $msgDiv.fadeOut(200, function() {
      $msgDiv.html(messages[msgIndex]).fadeIn(500);
      if(msgIndex >= messages.length)
        msgIndex = msgIndex % messages.length;
    });
  }, 3000);
});

看看jGrowl 非常好,可配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM