移动端滑动的时候判断某个元素是否出现
时间: 2023-10-10 22:04:44 浏览: 40
可以通过监听滚动事件来判断某个元素是否出现。具体步骤如下:
1. 获取需要判断的元素,可以通过 `.querySelector` 或 `document.getElementById` 等方法获取。
2. 监 `scroll` 事件,一般绑定在滚动容器上,如 `window` 或某个具有滚动条的元素。
3. 在 `scroll` 事件回调函数中,通过 `getBoundingClientRect` 方法获取元素相对于视口的位置信息,判断元素是否出现在视口中。
以下是示例代码:
```javascript
const targetEl = document.querySelector('#target');
const containerEl = document.querySelector('#container');
function handleScroll() {
const containerRect = containerEl.getBoundingClientRect();
const targetRect = targetEl.getBoundingClientRect();
if (targetRect.top >= containerRect.top && targetRect.bottom <= containerRect.bottom) {
console.log('Target element is fully visible in container!');
} else {
console.log('Target element is not visible in container!');
}
}
containerEl.addEventListener('scroll', handleScroll);
```
在上述代码中,`targetEl` 表示需要判断的元素,`containerEl` 表示滚动容器元素,在滚动容器中滚动时会触发 `handleScroll` 回调函数,该函数会判断元素是否出现在滚动容器可视区域中,并输出相应的日志信息。