viewport-check
v0.1.8
Published
Check element is entry or leave viewport
Maintainers
Readme
检测元素是否进入或者退出视口。
特性
可选择基于屏幕或者元素来判断是否进入视口,例如进入滚动容器
30%后,或者元素出现30%后输入方式多样化,可以输入数字
200,字符串30%,小数0.3可选择
autoDestory模式,进入一次视口后,移除监听,销毁对象横向纵向滚动判断
基于自定义容器的滚动,默认为
window元素高度自定义,可选择:
- 包括
margin, border, padding - 包括
border, padding,不包括margin - 包括
padding,不包括margin,border - 纯粹的高度,不包括
margin, border, padding
- 包括
效果查看
待添加特性
暂无
使用说明
- 安装
npm install viewport-check
- 使用
import ViewportCheck from 'viewport-check'
new ViewportCheck({
element:document.getElementById("target"),
offset:0.3,
baseAt:'target',
margin:true,
enter:(direction) => {
console.log('enter, the height include margin, border and padding! The enter direction is:'+direction)
},
leave:() => {
console.log('leave,The leave direction is:'+direction)
}
})
Options
|Attr|Description|Default value|Type|Required|
|:---|:---|:---:|:---:|:---:|
|element |需要监控的元素|/|HTMLElement[String]|true|
|context|滚动容器元素|window|HTMLElement[String]|false|
|offset|进出视口的偏移量|0.3|Number[String]|false|
|baseAt|偏移量基于元素还是滚动容器|target|(target/context)|false|
|padding|高度计算是否包括padding更多|true|Boolean|false|
|border|高度计算是否包括border更多|true|Boolean|false|
|margin|高度计算是否包括margin更多|false|Boolean|false|
|useCssComputed|是否使用css的高度设置更多|false|Boolean|false|
|autoDestroy|是否在进入视口后销毁|false|Boolean|false|
|horizontal|是否横向滚动|false|Boolean|false|
|enter|进入视口的回调函数|(direction)=>{}|Function|false|
|leave|离开视口的回调函数|(direction)=>{}|Function|false|
使用CSS高度设置
默认情况下使用getBoundingClientRect计算元素高度,但是当元素初始为scale(0)的情况,无法准确获取的高度,
因此需要使用getComputedStyle计算高度。
关于高度计算
在css的盒模型中,最外层的是margin,接着是border,接着是padding和height。
在ViewportCheck中,默认是margin:false,border:true, padding:true;这么做遵循了element.offsetHeight的配置。
因此,如果设定了margin:true,也就意味着包括margin,同样也包括了border和padding。
如果只想计算最纯粹的height,那么需要设定border:false, padding:false, 因为margin默认为false。
