2012-07-24 42 views
0

所以我想分離和appendTo基於窗口大小的div。以下是我目前擁有的。分離和AppendTo窗口調整大小

我正在用一個變量SOCIALBAR創建一個函數,賦值它等於#SOCIALMEDIA並將其分開。然後基於(document).ready和(window).resize的窗口大小,我調用SOCIALBARPlACEMENT函數,並且#SOCIALMEDIA或者適用於#TOP或#LEFT div。

這可以在(文檔).ready中正常工作,但對(窗口).resize不起作用。

事實上,如果我刪除document.ready,並離開window.resize,該函數仍然在頁面加載上運行,但不能在頁面大小調整上運行。

任何想法將不勝感激。謝謝!

function socialbarplacement() { 
    var socialbar; 
    socialbar = $("#socialmedia").detach(); 
    if (jQuery(window).width() < 1384) { 
     socialbar.appendTo("#top"); 
    } else { 
     socialbar.appendTo("#left"); 
    } 
}; 
$(document).ready(socialbarplacement()); 
$(window).resize(socialbarplacement()); 

回答

1

您所呼叫的功能立即而不是將它們作爲事件處理程序,嘗試:

$(document).ready(socialbarplacement); 
$(window).resize(socialbarplacement); 
/* 
someFunction() <-- invokes the function and resolves to the returned value 
someFunction <-- resolves to the function reference 
*/ 
+0

非常感謝!新的JavaScript和jQuery – 2012-07-24 18:33:38

0

我可能會做一些沿着這些線路(未測試的代碼):

$(window).resize(function(){ 
    var wnd = $(window), soc = $('#socialmedia'); 
    return function(){ 
     // might add a check to make sure you are not appending to the current parent. 
     soc.appendTo($(window).width() > 1384 ? '#left' : '#top'); 
    } 
}); 

當頁面加載時Resize會被觸發,所以你不需要準備好和調整大小。 同樣看着它,你正在執行的方法,當你真的應該通過名稱傳遞它。

0

我試過這樣...享受!

$(function() { 
 

 
    if (matchMedia) { 
 
\t var mq = window.matchMedia('(max-width: 1384px)'); 
 
\t var socialmedia = $("#socialmedia"); 
 
\t mq.addListener(WidthChange); 
 
\t WidthChange(mq); 
 
\t } 
 

 
\t function WidthChange(mq) { 
 
\t if (mq.matches && socialmedia) { 
 
\t \t socialmedia.appendTo("#top"); 
 
\t \t socialmedia = null; \t 
 
\t } else { 
 
\t \t socialmedia = $("#socialmedia").detach(); \t 
 
     socialmedia.appendTo("#left"); 
 
\t } 
 
\t }; 
 

 
});
<!doctype html> 
 
<html> 
 
<head> 
 
<meta charset="UTF-8"> 
 
<title>Untitled Document</title> 
 
    
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
    
 
</head> 
 

 
<body> 
 
    
 
    <div id="top"> 
 
    <div id="socialmedia">SOCIALMEDIA</div> <br> 
 
    **TOP** 
 
    </div> 
 
    
 
    <div id="left"> 
 
    <br> 
 
    **LEFT** 
 
    </div> 
 
    
 
</body> 
 
    
 
</html>