mirror of
https://github.com/ionic-team/ionic-framework.git
synced 2026-03-13 10:22:08 +08:00
feat(domUtil): add getPositionInParent function
Find an element's offset, then add it to the offset of the parent until we are at the direct child of parentEl. Use-case: find scroll offset of any element within a scroll container
This commit is contained in:
@@ -12,6 +12,24 @@
|
||||
|
||||
ionic.DomUtil = {
|
||||
|
||||
/*
|
||||
* Find an element's offset, then add it to the offset of the parent
|
||||
* until we are at the direct child of parentEl
|
||||
* use-case: find scroll offset of any element within a scroll container
|
||||
*/
|
||||
getPositionInParent: function(el, parentEl) {
|
||||
var left = 0, top = 0;
|
||||
while (el && el !== parentEl) {
|
||||
left += el.offsetLeft;
|
||||
top += el.offsetTop;
|
||||
el = el.parentNode;
|
||||
}
|
||||
return {
|
||||
left: left,
|
||||
top: top
|
||||
};
|
||||
},
|
||||
|
||||
ready: function(cb) {
|
||||
if(document.readyState === "complete") {
|
||||
window.rAF(cb);
|
||||
|
||||
40
test/js/utils/dom.js
Normal file
40
test/js/utils/dom.js
Normal file
@@ -0,0 +1,40 @@
|
||||
|
||||
describe('js/utils/dom', function() {
|
||||
|
||||
describe('getPositionInParent', function() {
|
||||
it('should return 0,0 if el===parentEl', function() {
|
||||
var el = {};
|
||||
expect(ionic.DomUtil.getPositionInParent(el, el)).toEqual({
|
||||
left: 0,
|
||||
top: 0
|
||||
});
|
||||
});
|
||||
it('should return 0,0 if el is null', function() {
|
||||
expect(ionic.DomUtil.getPositionInParent(null, null)).toEqual({
|
||||
left: 0,
|
||||
top: 0
|
||||
});
|
||||
});
|
||||
it('should return element offset{Top,Left} of el if el is parent\'s child', function() {
|
||||
var parent = {};
|
||||
var el = {parentNode: parent, offsetLeft: 3, offsetTop: 2};
|
||||
expect(ionic.DomUtil.getPositionInParent(el, parent)).toEqual({
|
||||
left: 3,
|
||||
top: 2
|
||||
});
|
||||
});
|
||||
it('should return added element offset{Top,Left} of all children up to parent', function() {
|
||||
var parent = {};
|
||||
var child1 = {parentNode: parent, offsetLeft: 5, offsetTop: 6};
|
||||
var child2 = {parentNode: child1, offsetLeft: 10, offsetTop: 11};
|
||||
expect(ionic.DomUtil.getPositionInParent(child1, parent)).toEqual({
|
||||
left: 5,
|
||||
top: 6
|
||||
});
|
||||
expect(ionic.DomUtil.getPositionInParent(child2, parent)).toEqual({
|
||||
left: 15,
|
||||
top: 17
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user