UNPKG

xxm-test-js

Version:
60 lines 2.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.scrollToBottom = scrollToBottom; /** * 滚动到容器底部。 * @param {HTMLElement | Window} [container=window] - 要滚动的容器,默认为window。 * @param {ScrollToOptions} [options={ behavior: 'smooth' }] - 滚动选项。 * @returns {Promise<void>} - 滚动完成的Promise。 * @example * ```javascript * // 使用示例 * // 滚动到页面底部 * scrollToBottom().then(() => { * // 滚动完成后执行其他操作 * console.log('已滚动到页面底部'); * }); * * // 滚动到指定元素的底部 * const element = document.getElementById('myElement'); * scrollToBottom(element).then(() => { * // 滚动完成后显示提示信息 * alert('已滚动到指定元素底部'); * }); * ``` */ function scrollToBottom(container = window, options = { behavior: 'smooth' }) { return new Promise((resolve) => { if (container === window) { const scrollHeight = document.documentElement.scrollHeight; container.scrollTo(Object.assign(Object.assign({}, options), { top: scrollHeight })); } else { if ('scrollLeft' in container) { const scrollHeight = container.scrollHeight; container.scrollTo(Object.assign(Object.assign({}, options), { top: scrollHeight, left: container.scrollLeft })); } else { const scrollHeight = 'scrollHeight' in container ? container.scrollHeight : document.documentElement.scrollHeight; // 为了确保 scrollHeight 是 number 类型,进行类型断言 container.scrollTo(Object.assign(Object.assign({}, options), { top: scrollHeight })); } } const checkScroll = () => { if ((container === window && window.scrollY + window.innerHeight >= document.documentElement.scrollHeight) || (container !== window && container.scrollTop + container.clientHeight >= container.scrollHeight)) { resolve(); } else { requestAnimationFrame(checkScroll); } }; requestAnimationFrame(checkScroll); }); } //# sourceMappingURL=scrollToBottom.js.map