在窗口调整大小时更改div的位置

时间:2016-01-11 11:33:19

标签: javascript jquery html css twitter-bootstrap

当屏幕尺寸小于481像素时,我试图改变div位置, 我在滑块后几乎在页面中间导航但在移动视图中它需要在滑块上方,这就是我尝试做的事情

<style type="text/css">
    .navPosition{position: relative;top: 0 !important;margin-bottom: 100px;}
 </style>
    <script src="js/bootstrap.js" type="text/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $width=$(window).width();
                if($width<481){
                        $("#navbg").addClass("navPosition");

                }

            });

        </script>

这是我的导航代码

<nav class="navbar" role="navigation" id="navbg">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
                                   切换导航                                                                                             
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav home-nav">
                <li>  <a href="#">Home</a></li>
                <li>  <a href="#">About us</a></li>
                <li>  <a href="#">Academics</a></li>
                <li>  <a href="#">News & Events</a></li>
                <li>  <a href="#">Contact us</a></li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>

但这对我不起作用,我是如何完成它的,请求帮助

1 个答案:

答案 0 :(得分:1)

尝试使用媒体查询来执行此操作

div#demo {
    position: relative;
    margin-top:10px;
}

@media only screen and (max-width: 481px) {
    div#demo{
        margin-top:200px;
    }
}

并在html端创建具有该ID的div

<div id='demo'> This is the demo for media query</div>

我为你创建了一个小jsfiddle