粘性元素的伪类
Pseudoclass for stickied element
假设我有一个元素position: sticky
。根据规范,它是 position: relative
和 position: fixed
的组合。那么,我怎么知道元素是否已经固定 ("stickied")?也许有什么伪类什么的?
可以使用getBoundingClientRect().top
属性的粘性元素。
假设您在可滚动包装器 div (id “wrapper”) 中有一个 sticky div (id “sticky”) :
CSS :
#wrapper {
overflow: auto;
}
#sticky {
position: sticky;
}
JS :
var stickyDiv = document.getElementById('sticky');
var stickyValue = 0; // will stick on the top of the div
stickyDiv.style.top = stickyValue + 'px';
document.getElementById('wrapper').addEventListener('scroll', function () {
var distance = stickyDiv.getBoundingClientRect().top;
if (distance <= (stickyValue + 1)) {
console.log('sticked');
}
else {
console.log('not sticked');
}
});
https://jsfiddle.net/9u4q8grq/2/
当然,如果您想将此应用到整个文档,您可以将事件侦听器目标更改为“window”。
正如@UncaughtTypeError 所说,请注意这是一项实验性功能,IE 不支持(但 Edge 可以)。
假设我有一个元素position: sticky
。根据规范,它是 position: relative
和 position: fixed
的组合。那么,我怎么知道元素是否已经固定 ("stickied")?也许有什么伪类什么的?
可以使用getBoundingClientRect().top
属性的粘性元素。
假设您在可滚动包装器 div (id “wrapper”) 中有一个 sticky div (id “sticky”) :
CSS :
#wrapper {
overflow: auto;
}
#sticky {
position: sticky;
}
JS :
var stickyDiv = document.getElementById('sticky');
var stickyValue = 0; // will stick on the top of the div
stickyDiv.style.top = stickyValue + 'px';
document.getElementById('wrapper').addEventListener('scroll', function () {
var distance = stickyDiv.getBoundingClientRect().top;
if (distance <= (stickyValue + 1)) {
console.log('sticked');
}
else {
console.log('not sticked');
}
});
https://jsfiddle.net/9u4q8grq/2/
当然,如果您想将此应用到整个文档,您可以将事件侦听器目标更改为“window”。 正如@UncaughtTypeError 所说,请注意这是一项实验性功能,IE 不支持(但 Edge 可以)。