2

我正在尝试制作一个菜单栏,根据屏幕上当前显示的 div 更改其大小。

这方面的东西:http: //housing.com/dsl

我当前的菜单 CSS 和页面其余部分的 HTML 标记如下:

<div class="menu">
    <a href="#content1">1</a>
    <a href="#content2">2</a>
</div>
<div class="content">
    <div class="content1" id="content1">
    </div>
    <div class="content2" id="content2">
    </div>
</div>

CSS

.menu{
    width:100%;
    height:80px;
    background-color: #336699;
    margin-top:-20px;
    margin: 0 auto; 
    margin-bottom: 10px;
    position:fixed;
}
4

1 回答 1

1

这并不难。您必须获取 div 的宽度,然后对其进行处理,如下所示:

$(document).ready(function() {
    // Get the div's width
    var divWidth = $("#content").width();
    // Update div's width
    $("#content").css("width", divWidth + 'px');
});

EDIT 1:

If you want you code to work dynamically as you change the browser's width, rather than on load, then you would have to bind it to .resize() event:

$(window).bind("resize", function(){
    // Get the div's width
    var divWidth = $("#content").width();
    // Update div's width
    $("#content").css("width", divWidth + 'px');
});

EDIT 2:

If you wish to do something as the page, let's say, scrolled down for 50px, then you would want to use .scroll() function to achieve this:

 $(document).ready(function(){
    $(window).scroll(function(){
        if ($(window).scrollTop() > 50){
            // Get the div's width
            var divWidth = $("#content").width();
            // Update div's width
            $("#content").css("width", divWidth + 'px');
        }
    });
});

Online demo example:

http://jsfiddle.net/ZVXBJ/1/

于 2013-10-13T13:37:10.677 回答