Javascript 如何根据另一个div设置一个div左位置?

Javascript 如何根据另一个div设置一个div左位置?,javascript,jquery,Javascript,Jquery,我有一个名为first的div,它的宽度可以是动态的,并且可以根据边距从左到右自动水平居中 .first { width:70%; background-color:#5b9a68; position:relative; margin:0 auto; } 另一个divsecond位置fixed .second { position:fixed; background-color:black; color:white; left:i

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

.first
{
    width:70%;
    background-color:#5b9a68;
    position:relative;
    margin:0 auto;
}
另一个div
second
位置
fixed

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

这里,当输入为零时,它应该从
first
div开始,这很好,但是当我们更改输入值时,我无法根据
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+"%");

});
比如说,如果我给50作为输入,那么我会把它放在65上,但这样我就不能完美地定位在
first
div的50上。同样,如果我给100%作为输入,这将转到外部

如何执行此操作如果输入为100,则第二个
div应位于第一个
div的末尾。
如果输入为50,则应位于第一个
中间

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

我想,您正在寻找50%和100%的场景

这应该做到:

JS:

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

$(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);
});

来自jQuery API文档:

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

因此:

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

这为我们提供了
的左坐标。第一个
div
即开始点。

您应该使用
位置:绝对
而不是
位置:固定
,然后将第二个div放在第一个div内,或者如果需要,为什么不将div并排浮动呢?您应该添加浮动:对不起,不应该有css更改@Petew3schools毕竟不是一个好的源代码..如果你这样做:
if(input==100){ex_pos=ex_pos-43;}
See Fiddle:我在寻找从1%到100%的所有连续百分比,我会等待@The Dark Knightperfect。我在我的小提琴第4,5行中所做的是你在一行中做的,就像在第6行中一样。我不知道这个偏移量,你能帮我理解jquery中的这个偏移量吗。感谢您的解决方案+1@Nikhil Pateladed做了一些解释。希望有帮助。:)
leftPos = $('.first').offset().left;