jQuery的CSS如何使用保证金:0自动
我是Jquery的新手。 我想知道我们如何使用margin:0 auto; jQuery脚本中的CSS代码。 任何人都可以请帮我吗? 代码如下:
<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>
其实我想要中心吧。 我怎样才能做到这一点?
你正在设置一切正确。 但是你不能将一个元素居中margin: auto
具有position: fixed
margin: auto
position: fixed
:
居中位置:固定元素
你也可以用jQuery来做到这一点:
使用jQuery在屏幕上居中放置DIV
你不能在jQuery中使用简写CSS,你将不得不单独设置每个页边距。
css({
"marginTop": "0",
"marginRight": "auto",
"marginBottom": "0",
"marginLeft": "auto"
})
你可以试试这个:
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。
链接地址: http://www.djcxy.com/p/75803.html