[英]How can I get the new offset of a moved element using Javascript?
I have an html table of data and each item in a row has a list_position
field which can be changed and then all of the items will be reordered to match the change on that item. 我有一个html数据表,一行中的每个项目都有一个list_position
字段,可以对其进行更改,然后所有项目将重新排序以匹配该项目的更改。
If I have a long list and I change an item from list_position
value from 1 to 1000, I would like the browser to automatically scroll down to that item after the list is re-ordered. 如果我的列表很长,并且将list_position
值从1更改为1000,我希望浏览器在列表重新排序后自动向下滚动到该项目。
Currently, with this code, I am scrolled to the item's initial position, not its current position. 目前,使用此代码,我可以滚动到项目的初始位置,而不是当前位置。
reorder: function (item, order, e) {
// reorder stuff ...
target = $(e.target).closest('tr');
this.scrollTo(target);
},
scrollTo: function (target) {
$('html,body').animate({
scrollTop: target.offset().top - 60
}, 1000);
return false;
}
If you just moved the element, its position likely hasn't yet been reflected in the DOM yet. 如果仅移动元素,则其位置可能尚未在DOM中得到反映。 One trick you can use is to wait until the browser's layout has been recalculated by using setTimeout
with a timeout of 0
. 您可以使用的一种技巧是,等待使用setTimeout
(超时值为0
重新计算浏览器的布局。
So instead of this.scrollTo(target);
所以代替this.scrollTo(target);
, try using: ,请尝试使用:
setTimeout(function() {
this.scrollTo(target);
}, 0);
For more information on why this works and when it's useful, please see this Stack Overflow question . 有关此方法为何起作用以及何时有用的更多信息,请参见此堆栈溢出问题 。
EDIT: Thanks to Bill Criswell for pointing out the Vue.nextTick
function , which is a more semantic way to wait for a DOM update (since you're already using the Vue.js library anyway). 编辑:感谢Bill Criswell指出了Vue.nextTick
函数 ,这是一种等待DOM更新的更语义的方法(因为无论如何您已经在使用Vue.js库)。 Using Vue.nextTick
, your code would become the following: 使用Vue.nextTick
,您的代码将变为以下内容:
Vue.nextTick(function() {
this.scrollTo(target);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.