所有方向展开框

时间:2014-02-07 15:21:46

标签: javascript jquery html css position

我有以下结构:

enter image description here

我的目标是当用户将鼠标悬停在框上时,他们应该展开并覆盖其他框而不会破坏UI。所以基本上盒子应该在每个指令中扩展20px,而每个其他元素都保持在同一个地方。请注意,我不知道盒子的确切大小,因为它们是负责任的。

我将这些方框定位如下:

#holder {
    width: 250px;
    background-color: #FFCCCC;
    overflow: hidden;
    padding: 15px;
}

.box {
    width: 45%;
    height: 50px;
    border: 1px grey solid;
    float: left;
    margin-bottom: 15px;
}

.box:nth-child(odd) {
    float: right;
}

使用下面的HTML:

<div id="holder">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>

我正在使用jQuery处理事件。

$(document).ready(function(){
$(".box").mouseenter(function(){
      var _this = $(this);
      var newWidth = parseInt(_this.css("width")) + 40,
          newHeight = parseInt(_this.css("height")) + 40;

    _this.
        css("z-index", 99).
        animate({
            width: newWidth + "px",
            height: newHeight + "px",
            marginTop: "-20px",
            marginLeft: "-20px"
        }, 1000);
});

 $(".box").mouseleave(function(){
      var _this = $(this);
      var newWidth = parseInt(_this.css("width")) - 40,
          newHeight = parseInt(_this.css("height")) - 40;

    _this.
    css("z-index", 1).
    animate({
        width: newWidth + "px",
        height: newHeight + "px",
        marginTop: "0px",
        marginLeft: "0px"
    }, 1000);
});
});

这是小提琴:http://jsfiddle.net/3T89h/

1 个答案:

答案 0 :(得分:1)

我能想到的最简单的方法是绝对定位(虽然可能有更简洁的方式)。

您需要申请

position:absolute;

到每个方框,给它一个固定的高度/宽度(百分比不会真正起作用)并手动定位,例如

http://jsfiddle.net/3T89h/1/

修改

如果你的盒子需要响应,有不确定的高度和宽度,然后仍然可以用类似的方法做到这一点。

您可以将原始框用作容器,

position:relative;

然后在其中保留您的实际内容绝对定位,这是一个例子:

http://jsfiddle.net/3T89h/2/

所以基本上你现在有一个盒子作为一个响应包装器,它包含一个具有所需效果的内盒,它与包装器的尺寸相匹配。然后可以显着改变设计,但不会改变您想要的javascript效果,例如:http://jsfiddle.net/3T89h/3/