2016-09-22 74 views
0

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

JSBIN:http://jsbin.com/lanako/7/edit?html,js,output

<!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)有一个流体测量(%),所以左边的位置改变。

该方程最初的工作原理,但我想调整浏览器的大小,方程pf.css(),它计算出(#first) css left属性执行。不幸的是,我设置的$(window).resize函数不起作用,因此(#first)的左侧属性保持不变。我想要的最终目标是不管浏览器的大小,元素将由6个像素(右边距#somepara 6像素)分隔。

任何帮助将不胜感激!

回答

1

#somepara的位置发生改变,当你调整,所以你需要在每次调用offcss()功能(而不是只在第一负载)时采取的p.offset()值。

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

关于调整大小,它看起来像它确实是你想要的。

检查这个例子:
http://jsbin.com/dewazuyuqo/1/edit?html,js,output

+0

谢谢!你介意解释为什么这个工作,而我的不工作?变量offset取代了p.offset(),否则它是完全一样的...... – the12

+1

你的'offset'是一个固定值,而在我的解决方案中,我通过调用'p.offset'来获取“当前”值()'(每改变一次窗口宽度都会改变)。 – Dekel

相关问题