简体   繁体   English

在JQuery中,如何在用户单击鼠标从DOM中删除元素后,如何获取元素的offset()。top

[英]In JQuery how do I get the offset().top of an element after a user removes an element from the DOM with a click

Long title I know. 我知道长标题。 Sorry. 抱歉。

I just want to know how I get the new position after a click event that removes an element. 我只想知道在单击事件中删除元素后如何获得新职位。 Essentially I have a bar that is removed once the user does a click. 基本上,我有一个栏,一旦用户单击就将其删除。 There are some buttons on my page that have a fixed position when the distance of the scroll is greater than the offset so it looks like they unhook. 当滚动的距离大于偏移量时,页面上有一些按钮处于固定位置,因此看起来好像它们已脱钩。

I tried to do offset().top in a callback after a click event, but it just outputs the original offset value not the distance minus the element removed. 我尝试在click事件之后在回调中执行offset()。top,但它仅输出原始偏移值,而不是距离减去所删除元素的距离。 This makes the buttons just look like they jump into the fixed position as it's not removing the clicked element's height from the offset. 这使得按钮看起来像是跳入了固定位置,因为它没有从偏移量中删除被单击元素的高度。

var distance = $('.anchor-con').offset().top;

alert($('.anchor-con').offset().top);

$(".icon-cross").click(function(){

    distance = $('.anchor-con').offset().top;
    alert($('.anchor-con').offset().top);

});

Hope that makes sense. 希望有道理。 Some help on this would be great. 对此会有一些帮助。

Thanks 谢谢

Rob

You can use mouseup event instead of click as you want to know the new position after the click. 您可以使用mouseup事件代替click因为您想在单击后知道新位置。

try the following code 试试下面的代码

var distance = $('.anchor-con').offset().top;

alert($('.anchor-con').offset().top);

$(".icon-cross").mouseup(function(){
    distance = $('.anchor-con').offset().top;
    alert($('.anchor-con').offset().top);
});

so you want to know the new top of your anchor after the bar is removed by a click. 因此您想通过单击将栏删除后知道锚点的新顶部。 use a setTimeout in your click handler with 0 delay just to ensure that the bar is removed. 请在您的点击处理程序中使用setTimeout(延迟为0),以确保删除该栏。 the way you are doing does not guarantee that bar is already removed because the bar removal click handler may be executing after your position calculator handler. 您执行的方式不能保证条形图已被删除,因为条形图删除单击处理程序可能在位置计算器处理程序之后执行。 following will work if i correctly understood your question. 如果我正确理解您的问题,下面的方法将起作用。

var distance = $('.anchor-con').offset().top;    
alert($('.anchor-con').offset().top);

$(".icon-cross").click(function(){
    setTimeout(function(){
        distance = $('.anchor-con').offset().top;
        alert($('.anchor-con').offset().top);
    }, 0);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM