@mdui/jq
Version:
拥有和 jQuery 相似 API 的轻量级 JavaScript 工具库
67 lines (66 loc) • 2.14 kB
JavaScript
import { $ } from '../$.js';
import { extend } from '../functions/extend.js';
import { isFunction } from '../shared/helper.js';
import './css.js';
import './each.js';
import './position.js';
const get = (element) => {
if (!element.getClientRects().length) {
return { top: 0, left: 0 };
}
const { top, left } = element.getBoundingClientRect();
const { pageYOffset, pageXOffset } = element.ownerDocument
.defaultView;
return {
top: top + pageYOffset,
left: left + pageXOffset,
};
};
const set = (element, value, index) => {
const $element = $(element);
const position = $element.css('position');
if (position === 'static') {
$element.css('position', 'relative');
}
const currentOffset = get(element);
const currentTopString = $element.css('top');
const currentLeftString = $element.css('left');
let currentTop;
let currentLeft;
const calculatePosition = (position === 'absolute' || position === 'fixed') &&
(currentTopString + currentLeftString).includes('auto');
if (calculatePosition) {
const currentPosition = $element.position();
currentTop = currentPosition.top;
currentLeft = currentPosition.left;
}
else {
currentTop = parseFloat(currentTopString);
currentLeft = parseFloat(currentLeftString);
}
const computedValue = isFunction(value)
? value.call(element, index, extend({}, currentOffset))
: value;
$element.css({
top: computedValue.top != null
? computedValue.top - currentOffset.top + currentTop
: undefined,
left: computedValue.left != null
? computedValue.left - currentOffset.left + currentLeft
: undefined,
});
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
$.fn.offset = function (value) {
// 获取坐标
if (!arguments.length) {
if (!this.length) {
return undefined;
}
return get(this[0]);
}
// 设置坐标
return this.each(function (index) {
set(this, value, index);
});
};