2014-10-07 46 views
0

我對jquery相當陌生,這有點不在我的聯盟中。如何在某些頁面寬度上使用jquery向上/向下移動div

我想一個div移動到不同的位置,我可以做到:

$('#searchbar').insertAfter('.search-item'); 

現在我想要做的就是寫一個聲明,如果說,如果屏幕寬度爲800像素做:

$('#searchbar').insertAfter('.search-item'); 

else(屏幕寬度大於800px)將其放回到原始位置。

我試過搜索,但它似乎很具體。

任何想法或是否有更好的方法來實現我想要的?

在此先感謝您的幫助!

+0

通過屏幕的寬度,你實際上意味着用戶屏幕的分辨率?或者只是瀏覽器窗口或視口的寬度? – 2014-10-07 22:20:06

+0

@JamesHay瀏覽器/視口的寬度。它主要用於移動導航。 – user3330820 2014-10-07 22:21:33

+0

您是否考慮過使用[CSS媒體查詢](http://css-tricks.com/css-media-queries/)? – Jonathan 2014-10-07 22:22:30

回答

0

你可以做這樣的事情用jQuery:

$(window).on("resize", function() { //or $(window).resize(function() { 
    var w = $(this).width(); 
    if (w < 800) { 
     //do less than action 
    } else { 
     //do else action 
    } 
}); 

正如一個上面提到的評註者,你也許能夠做這樣的事情使用CSS。

+0

這將工作。我只是不知道如何讓div回到原來的位置。 – user3330820 2014-10-07 22:31:09

+0

好吧,我最終只是插入原來的位置,所以這似乎是完美的。謝謝! – user3330820 2014-10-07 22:33:04

-1

在移動它之前,您可以在其父容器中獲取該項目的索引,然後使用畫面寬度將其移回。

像這樣的事情

var searchbar = $('#searchbar'); 

// Get the parent container of the bar. 
var parent = searchbar.parent(); 

// Get the starting location of the bar. 
var index = parent.index(searchbar); 

if($(window).width() >= 800){ 
    // Insert the bar after the '.search-item' 
    searchbar.insertAfter('.search-item'); 
} 
else{ 
    // Insert the bar in its original location 
    $(parent.children()[index]).before(searchbar); 
} 
相關問題