Div宽度在点击时展开/缩小

Sal*_*lem 4 html javascript jquery mootools

对于我为自己和朋友制作的网站,我有一个div容器/包装,其中包含2个其他div:一个占据左半部分,背景为黑色,另一个占据右边白色背景.从本质上讲,这让我得到一个分裂的彩色背景.每个div都有一半的徽标.这是暂时托管的页面,以便您可以看到它.

http://djsbydesign.com/tempsite/index.htm

无论如何,我想在页面的左侧和右侧有链接,点击它们会使它们各自的div从50%扩展到100%.我有一些想法,但我不确定如何去做这个(我对javascript很新).第一种方法是将扩展div的z-index设置为高于非扩展的z-index,然后扩展(以某种方式),另一种是将扩展div扩展到100%而另一个缩小到0%,同等比率.

底线是,我不知道如何去做这件事.我不介意使用mootools或jQuery作为记录.

Dav*_*mas 9

以下似乎有效:

$('#left-bg, #right-bg').click(
    function(){
        $(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
    });
Run Code Online (Sandbox Code Playgroud)

虽然我不确定你打算如何把'其他'带回来div.

JS小提琴演示.


编辑添加一个按钮(通过jQuery),允许将两个divs恢复为原始尺寸:

$('#left-bg, #right-bg').click(
    function(){
        $(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
        $('<button class="show">Show all</button>')
            .appendTo('#wrapper');
    });

$('.show').live('click',
                function(){
                    $('#left-bg').animate(
                        {
                            'width': '50%'
                        },600);
                    $('#right-bg').animate(
                        {
                            'width': '50%'
                        },600);
                    $(this).remove();
                });
Run Code Online (Sandbox Code Playgroud)

更新了JS Fiddle.


编辑在评论中解决OP留下的问题:

动画完成后有没有办法让页面重定向?

是的,只需添加该行 window.location.href = "http://path.to.url.com/";

$('#left-bg, #right-bg').click(
    function(){
        $(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
        $('<button class="show">Show all</button>')
            .appendTo('#wrapper');
        window.location.href = "http://www.google.com/" // <-- this line redirects.
    });

$('.show').live('click',
                function(){
                    $('#left-bg').animate(
                        {
                            'width': '50%'
                        },600);
                    $('#right-bg').animate(
                        {
                            'width': '50%'
                        },600);
                    $(this).remove();
                });
Run Code Online (Sandbox Code Playgroud)

更新了JS Fiddle.


编辑以回应错误报告(在评论中):

另一个错误(简单修复)是,无论何时单击其中一个div,它都会创建一个新按钮.所以说你点击左半边,它展开并填充页面等,然后你再次点击它(它现在在页面的任何地方).它会尝试添加第二个按钮.

要防止第二个按钮被添加到div刚刚添加if:

$('#left-bg, #right-bg').click(
    function(){
        if (!$('.show').length) {
            $(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
            $('<button class="show">Show all</button>')
                .appendTo('#wrapper');
            window.location.href = "http://www.google.com/" // <-- this line redirects.
        }
    });
Run Code Online (Sandbox Code Playgroud)

只要选择器没有返回匹配项,它只会附加一个button或者确实为divs 添加动画.$('.show')

但是,如果您也通过单击按钮重定向到另一个页面,它不应该是一个问题,因为原始页面上的jQuery都不会执行/能够访问用户被重定向到的页面(除非它是您自己的域上的页面,并且您已明确选择添加相同的页面button).