2012-04-25 42 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。我弄清楚我做错了什么。这里是工作代码:)