* 滚动页面 * * 支持三种调用方式: * 1. scroll(y) - 垂直滚动到 y 位置 * 2. scroll(x, y) - 滚动到 (x, y) 位置 * 3. scroll(selector, optional?) - 滚动到元素位置 * - optional: boolean 或 ScrollIntoViewOptions(传递给 element.scrollIntoView) * * @returns {ZBrowserClient} this
(...args)
| 640 | * @returns {ZBrowserClient} this |
| 641 | */ |
| 642 | scroll(...args) { |
| 643 | if (typeof args[0] === 'number') { |
| 644 | if (args.length === 1) { |
| 645 | return this.evaluate((y) => { |
| 646 | window.scrollTo(window.scrollX, y) |
| 647 | }, args[0]) |
| 648 | } |
| 649 | if (args.length === 2 && typeof args[1] === 'number') { |
| 650 | return this.evaluate( |
| 651 | (x, y) => { |
| 652 | window.scrollTo(x, y) |
| 653 | }, |
| 654 | args[0], |
| 655 | args[1] |
| 656 | ) |
| 657 | } |
| 658 | throw new Error('scroll: parameter error') |
| 659 | } |
| 660 | |
| 661 | if (typeof args[0] === 'string') { |
| 662 | if (args[1] !== undefined) { |
| 663 | // scroll(selector, optional) - 使用 scrollIntoView |
| 664 | return this.evaluate( |
| 665 | (selector, optional) => { |
| 666 | const el = document.querySelector(selector) |
| 667 | if (!el) { |
| 668 | throw new Error('scroll: unable to find element by selector "' + selector + '"') |
| 669 | } |
| 670 | el.scrollIntoView(optional) |
| 671 | }, |
| 672 | args[0], |
| 673 | args[1] |
| 674 | ) |
| 675 | } |
| 676 | // scroll(selector) - 默认滚动到元素位置 |
| 677 | return this.evaluate((selector) => { |
| 678 | const el = document.querySelector(selector) |
| 679 | if (!el) { |
| 680 | throw new Error('scroll: unable to find element by selector "' + selector + '"') |
| 681 | } |
| 682 | const rect = el.getBoundingClientRect() |
| 683 | window.scrollTo(rect.left, rect.top) |
| 684 | }, args[0]) |
| 685 | } |
| 686 | |
| 687 | throw new Error('scroll: parameter error') |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | module.exports = { ZBrowserClient } |