相对于另一个不工作的定位元件

Positioning element relative to another not working

本文关键字:定位 工作 另一个 相对于      更新时间:2023-09-26

我试图定位一个元素相对于另一个使用jQuery offset()方法,我试图找出为什么$(window).resize函数不工作。

JSBIN: http://jsbin.com/lanako/7/edit?html、js、输出

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<style>

div{
display:inline-block;
position:relative;
height:200px;
width:200px;
border:solid black;    
}
#somepara{
border: solid blue;
position:relative;
left:20%;
}
</style>
<body>
  <div id ="first"> FIRST</div>
  <div id = 'somepara'>  </div>

</body>
</html>
JavaScript:

var p = $( "#somepara" );
var pf =  $('#first');
var offset = p.offset();
p.html( "left: " + offset.left);
function offcss(){
pf.css({'left': offset.left + 6 + "px"});
}
$(document).ready(function(){
  offcss();
    $(window).resize(function(){
        offcss();
    });

});

我基本上抓住第二个元素('#somepara')offset().left,并试图将('#first')的css设置为(#somepara)的右6个像素。注意:(#somepara)有一个流体测量(%),因此左侧位置发生变化。

这个等式最初是有效的,但是我想在调整浏览器的大小后,为计算(#first)的css left属性的等式pf.css()执行。不幸的是,我设置的$(window).resize函数不起作用,因此(#first)的左侧属性保持不变。我想要的最终目标是无论浏览器大小如何,元素将被6个像素隔开(#first#somepara右6个像素)。

任何帮助都将非常感激!

#somepara的位置在调整大小时发生变化,因此每次调用offcss()函数时都需要取p.offset()的值(而不仅仅是在第一次加载时)

function offcss() {
    pf.css({'left': p.offset().left + 6 + "px"});
}

关于大小的调整,它似乎正是你想要的。

检查这个例子:
http://jsbin.com/dewazuyuqo/1/edit?html、js、输出