如何根据另一个div使div保持位置?

时间:2013-09-13 13:02:38

标签: javascript jquery

我有一个名为first的div,其宽度可以是动态的,并且可以根据左边的边距水平居中到自动

.first
{
    width:70%;
    background-color:#5b9a68;
    position:relative;
    margin:0 auto;
}

另一个位置为second

的div fixed
.second
{
    position:fixed;
    background-color:black;
    color:white;
    left:input;
}

HTML

<div class="first">content</div>
<div class="second">Left Value</div>

我希望这个second div根据first div来定位。这里的问题是second div位置是fixed所以它是根据屏幕宽度定位所以我尝试使用此脚本根据first div。

定位它
$(document).ready(function(){
    var input=0;

    var first_width = $(".first").width() / $('.first').parent().width() * 100;  
    var pos = (100-first_width)/2;//getting the empty part
    var ex_pos=pos+input;

    $('.second').css("left",ex_pos+"%");

});

这里当输入为零时,它应该从first div的开头开始,这很好,但是当我们改变输入值时,根据first div得不到准确的百分比定位。

比如说,如果我给50作为输入,那么我将它放在65但是这种方式不能完美地定位在50 first div中。如果我给出100%作为输入,这将在外面

如果输入为100则如何执行此操作,则second div应位于first div的末尾。 如果输入为50,那么它应该在first的中间位置。

Output With 0% left position

Output With 50% left position

Output With 100% left position

注意 - 我不想更改或编辑css。我想单独用脚本来做。 的 Check Fiddle

2 个答案:

答案 0 :(得分:3)

你走了:

$(document).ready(function () {
    var input = 0,
        firstWidth = $('.first').width(),                    // width of first div
        secondWidth = $('.second').width(),                  // width of second div
        offset = (input * (firstWidth - secondWidth)) / 100, // % to shift
        leftPos = $('.first').offset().left;                 // left position of first div

    $('.second').css("left", leftPos + offset);
});

JSFiddle

来自jQuery API文档:Link

  

.offset()方法允许我们检索元素 相对于文档的当前位置
  它返回一个包含top和left属性的对象。

所以:

leftPos = $('.first').offset().left;

这给了我们.first div的左坐标,即它开始的点。

答案 1 :(得分:0)

我猜,你正在寻找50%和100%的情景。

这应该这样做:

JS:

if(input===100){
    ex_pos = ex_pos - 43;
}else if(input===50){
    ex_pos = ex_pos - 13;
}

FIDDLE