Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

某一元素进入视窗后=>触发事件 #48

Open
jiangjiu opened this issue Jul 30, 2018 · 0 comments
Open

某一元素进入视窗后=>触发事件 #48

jiangjiu opened this issue Jul 30, 2018 · 0 comments
Labels

Comments

@jiangjiu
Copy link
Owner

某一元素进入视窗后=>触发事件

需求背景

我们经常会遇到一些业务场景,比如某一个dom元素露出来后,打一个点(或者触发其他操作)。

常规解法

监听滚动事件,判断滚屏高度,处理不好的话,会带来性能问题。

IntersectionObserver API

Intersection Observer API

这是一个实验中的API,原生实现有兼容性问题,好在w3c官方提供了polyfill,我们业务可以正常使用。

(官方的polyfill实现的很巧妙)

Example

安装

npm install 'intersection-observer';

引入+一个简单的封装

import 'intersection-observer';
/**
 * inview 某一dom元素进入视窗后,触发一次事件
 *
 * @param {Element} el DOM元素
 * @param  {Function} callback 回调
 */
export function inview(el, callback) {
    if (!el || !callback) {
        throw new Error('inview needs el && callback! ');
    }
    const io = new IntersectionObserver(entries => {
        if (entries[0].isIntersecting) {
            callback();
            io.disconnect();
        }
    });
    io.observe(el);
}

上面的inview方法接收一个原生dom元素和一个回调事件,可以让这个元素进入视野后触发回调。

业务中使用

// 获取一个dom元素
// 在san的模板中也可以通过s-ref获取
const dom = document.querySelector('.shareToFrieds');

// 当这个dom元素滚动到屏幕中,打点
inview(dom, () => {
    this.sendLog('shared!!');
});
@jiangjiu jiangjiu added the demo label Jul 30, 2018
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant