2015-06-16 41 views
0

我已經寫了一些東西,允許我動態創建div的,但我有幾個問題使它淡出使用Jquery。該div目前正在出現但不會消失。關於動態創意div的jQuery fadeOut

<script src="/socket.io/socket.io.js"></script> 
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> 
<script src="http://code.jquery.com/jquery-1.11.1.js"></script> 
    <script> 
    socket.on('hello', function (answer) { 
     console.log('hello?: ' + answer); 
     var div = document.createElement("div"); 
     div.setAttribute("id", "#fade"); 
     div.style.margin = Math.floor((Math.random() * 400) + 1) + "px"; 
     div.style.width = "100px"; 
     div.style.height = "100px"; 
     div.style.background = "red"; 
     div.style.color = "white"; 
     div.innerHTML = "Hello"; 
     document.body.appendChild(div); 
     $("#fade").delay(3000).fadeOut("slow"); //Fadeout 
    }); 
    </script> 

    <body> 
    </body> 
+0

嘗試在$(文件)。就緒包裝這個(函數(){});也許? – neilsimp1

+0

@ neilsimp1剛剛那樣做,仍然沒有。 http://puu.sh/ir3NO/aba6e537c8.png div出現,但不褪色 –

回答

1

Vanilla DOM函數不使用#號來標識ID。更改

div.setAttribute("id", "#fade"); 

div.setAttribute("id", "fade"); 
+0

原來我錯了,仍然沒有工作 –

3

你的ID錯誤,你將它設置爲#fade,不只是fade,設置當你不添加哈希,但爲什麼不使用jQuery

socket.on('hello', function (answer) { 

    $('<div />', { 
     id : 'fade', 
     css : { 
      margin  : Math.floor((Math.random() * 400) + 1), 
      width  : 100, 
      height  : 100, 
      background : 'red', 
      color  : 'white' 
     }, 
     html : 'Hello' 
    }).delay(3000).fadeOut('slow').appendTo('body'); 
}); 

FIDDLE