2012-04-25 43 views
2

我是Jquery的新手。我想知道我們如何使用margin:0 auto; jQuery腳本中的CSS代碼。任何人都可以請幫我嗎?這裏的代碼:Jquery CSS如何使用保證金:0自動

<style> 
#fixed-bar { 
    padding: 0; 
    background-color: black; 
    z-index: 100; 
} 
</style> 
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> 

<script> 
$(function() { 
    $("#fixed-bar") 
    .css({ 
     "position": "fixed", 
     "width": "960px", 
     "margin": "0 auto", 
     "top": "0px", 

}) 
    .hide(); 
    $(window).scroll(function() { 
    if ($(this).scrollTop() > 400) { 
     $('#fixed-bar').fadeIn(200); 
    } else { 
     $('#fixed-bar').fadeOut(200); 
    } 
    }); 
}); 
</script> 
<div id='fixed-bar'> 
    Hello 
</div> 

其實我想要中心吧。我怎樣才能做到這一點?

+5

你爲什麼試圖用jQuery來設計吧?如果可能的話,你應該在CSS中保留你的樣式。 – chipcullen 2012-04-25 14:40:01

+0

你想水平或真實地居中放置吧檯嗎? – Maverick 2012-04-25 14:41:14

+0

我無法居中吧。你可以請張貼工作代碼,無論是與CSS或風格的酒吧與jQuery?我會很感激你的幫助。 – 2012-04-25 14:42:25

回答

2

您正在設置一切正確。 但你不能中心的元素與margin: autoposition: fixed

Center a position:fixed element

你也可以使用jQuery做到這一點:

Using jQuery to center a DIV on the screen

+0

感謝Binarious。是的,我們不能使用margin:auto:position:fixed :.但添加左:0和右:0它的作品:)再次感謝。這裏是我對上面的CSS文件所做的更改。 [code]#fixed-bar { position:fixed; margin-left:auto; margin-right:auto; 填充:0; background-color:black; z-index:100; left:0; right:0; [code] – 2012-04-25 14:57:28

-2

有更好的方法來使用中心jQuery的一個div,例如將其設置爲絕對位置並查找其寬度,視口寬度以及基於這些數字設置偏移量:

$('.mydiv').css("left", (($(window).width() - this.outerWidth())/2) + $(window).scrollLeft() + "px"); 
+5

'margin:0 auto'將會在沒有父對象的情況下工作:text-align:center。有問題的元素只需要聲明寬度就是全部。 – chipcullen 2012-04-25 14:46:59

+0

是的,對,對不起,我錯過了。儘管如此,我仍然會使用jQuery解決方案。 – 2012-04-25 14:48:15

+0

請解釋爲什麼您會使用jQuery解決方案代替簡單的CSS解決方案? – Sparky 2012-04-25 15:20:09

1

您不能在jQuery中使用簡寫CSS,您必須單獨設置每個邊距。

css({ 
    "marginTop": "0", 
    "marginRight": "auto", 
    "marginBottom": "0", 
    "marginLeft": "auto" 
}) 
+0

不知道爲什麼我得到所有downvotes。根據jQuery文檔,他的邊距不會被應用(就在這個例子之前):http://api.jquery.com/css/#css1 – 2012-04-25 15:38:53

-1

你可以試試這個:

HTML:

<div id="fixed-bar"> 
    <p>Test</p> 
</div> 

CSS:

body { 
    position : relative; 
} 

#fixed-bar { 
    padding: 0; 
    background-color: black; 
    z-index: 100; 
    width: 960px; 
} 

的JavaScript:

$("#fixed-bar").css({ 
       "position" : "absolute", 
       "left" : (($(window).width() - $("#fixed-bar").outerWidth())/2) + $(window).scrollLeft() + "px" }) 
       .hide(); 

$(window).scroll(function() { 
    if ($(this).scrollTop() > 400) { 
     $('#fixed-bar').fadeIn(200); 
    } else { 
     $('#fixed-bar').fadeOut(200); 
    } 
}); 

這樣,無論屏幕大小如何,您的元素都將水平居中。不要忘記在你的HTML中包含jQuery。

+0

不,它不工作。感謝@Husar。我弄清楚我做錯了什麼。這裏是工作代碼:)