javascript 少见却很实用的原生 API

490 阅读1分钟

javascript 原生 API

1、getBoundingClientRect()

getBoundingClientRect() 方法返回一个 DOMRect 对象,对象包含了元素相对于视口的位置信息。

使用方法:

domRect = element.getBoundingClientRect();

返回元素的 left, top, right, bottom, x, y, width, and height 值; 如图:

截屏2022-04-20 上午11.02.28.png

下面我们用 getBoundingClientRect 来实现当元素出现在视口时进行接口调用:

const element = document.getElementById(id);
const rect = element.getBoundingClientRect();
const rootElement = document.documentElement; // 返回 element 的根元素(例如 <html> 的元素)
const positionTop = topElement.scrollTop;
if (rect.top > positionTop) {
    // todo 业务逻辑...
    api('xxx').then()
}

在小程序中,我们没有 getBoundingClientRect 方法,可以使用以下方法替代: 在 chameleon 框架搭建的小程序中,我们使用 chameleon-api 提供的 api 获取元素的位置信息。 用法如下:

<template>
    <view>
        ...
        <view id="avatar">...</view>
    </view>
</template>
<script>
import cml from 'chameleon-api' // 引入 api

class Index {
    ...
    mounted() {
        cml.getRect('avatar', this).then(rec => {
            const {height, width, top, bottom} = rec
            
            // 当当前元素高度大于 700 时,处理一些业务逻辑
            if(cml.cpx2px(height) > 700) { // cml.cpx2px 输入一个px值得到当前设备上对应的cpx值
                // todo something...
            }
            console.log(height, width, top, bottom)
        })
    }
}
</script>

2、once: true

once 是 addEventListenner 自带的一个属性,用于只执行一次。

<div class="outer">
    outer
    <div class="middle" target="_blank">
        middle
    </div>
</div>
let outer = document.getElementsByClassName('outer') [0]
let once = {
    once: true
}

function onceHandler(event) {
    alert('outer, once');
}

outer.addEventListener('click', onceHandler, once);

once 在处理重复上报日志等业务中比较有用。