HTML对象不断增长并推动其他人

时间:2013-12-30 01:01:27

标签: javascript jquery html css

我怎么能这样做,以便给出两个元素让我们说这些框: enter image description here

如果我点击一个,它会增长,而另一个会缩小,反之亦然: enter image description here

我该怎么做?

我已经看过CSS使用焦点标签并调整宽度。但我有两个问题,首先我怎么能影响另一个元素,其次,据我所知,调整宽度只会拉伸它们。我看到人们改变了浮动元素的方式来处理它,但我不想在页面上移动它们来做这件事。

3 个答案:

答案 0 :(得分:4)

以下是2个没有Javascript / jQuery的示例:

纯CSS - 点击时触发:(example)

使用CSS中的复选框hack,当复选框为:checked时,您可以有效切换元素的宽度。这是CSS的一部分:

input[type=checkbox]:checked ~ .red {
    width:70%;
}
input[type=checkbox]:checked ~ .green {
    width:20%;
}

转到example获取完整的CSS。

<强> HTML

<input type="checkbox" id="toggle" />
<div class="red">
    <label for="toggle"></label>
</div>
<div class="green">
    <label for="toggle"></label>
</div>

您可能也对我制作的原始example感兴趣。它需要采用不同的方法,但它并不完全有效。

纯CSS - 悬停时触发:(example)

不幸的是,相邻的选择器和一般的兄弟选择器都不能选择以前的元素,因此这有点困难。我在主要元素之前放置了2个通用元素,以便在某种程度上解决这个问题。

.greenS:hover, .greenS:hover ~ .green,
.redS:hover, .redS:hover ~ .red {
    width:72%;
}
.greenS:hover ~ .redS, .greenS:hover ~ .red,
.redS:hover ~ .greenS, .redS:hover ~ .green {
    width:22%;
}

<强> HTML

<div class="redS"></div><div class="greenS"></div>
<div class="red"></div>
<div class="green"></div>

由于这被标记为JS / jQuery,因此这里有两种替代解决方案。

JS / jQuery - 点击时触发:(example)

$('.red, .green').click(function(){
    $('.red').toggleClass('expanded')
    .next('.green').toggleClass('contracted');
});

JS / jQuery - 悬停时触发:(example)

$('.red').hover(function(){
    $(this).toggleClass('expanded')
    .next('.green').toggleClass('contracted');
});
$('.green').hover(function(){
    $(this).toggleClass('expanded')
    .prev('.red').toggleClass('contracted');
});

答案 1 :(得分:0)

请参阅jQuery .animate() method文档。

jsfiddle上的示例:

.box {
    width: 100px;
    height: 100px;
    display: inline-block;
}

#box1 {
    background: red;
}

#box2 {
    background: blue;
}

<div class="box" id="box1"></div>
<div class="box" id="box2"></div>

$('.box').click(function() {
    var currentWidth = $(this).outerWidth(),
        siblingCurrentWidth = $(this).siblings('.box').outerWidth();

    $(this).animate({'width' : currentWidth/2})
    .siblings('.box').animate({'width' : siblingCurrentWidth*2});
});

这是一个非常简单的例子,有几个缺陷,但它证明了你的目的是什么的可能性。

答案 2 :(得分:0)

简单示例http://jsfiddle.net/PeLub/(修改您需要的方式)。

<div class="box" id="first"></div>
<div class="box" id="second"></div>

 $("#first").click(function(){
  $(this).animate({width:'50px'}, 500);
  $("#second").animate({width:'150px'}, 500);    
 });

 $("#second").click(function(){
  $(this).animate({width:'50px'}, 500);
  $("#first").animate({width:'150px'}, 500);    
 });