Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 粘滞元素的伪类_Html_Css_Sticky - Fatal编程技术网

Html 粘滞元素的伪类

Html 粘滞元素的伪类,html,css,sticky,Html,Css,Sticky,假设我有一个位置为:sticky的元素。根据规范,它是位置:相对和位置:固定的组合。那个么,我怎么知道元素是否已经固定(“粘滞”)了呢?可能有伪类之类的吗?您可以使用粘性元素的getBoundingClientRect().top属性。 假设您在可滚动包装器div(id“wrapper”)中有一个sticky div(id“sticky”): CSS: #wrapper { overflow: auto; } #sticky { position: sticky; } JS:

假设我有一个位置为:sticky的元素。根据规范,它是
位置:相对
位置:固定
的组合。那个么,我怎么知道元素是否已经固定(“粘滞”)了呢?可能有伪类之类的吗?

您可以使用粘性元素的
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');
    }
});
var stickyDiv=document.getElementById('sticky');
var stickyValue=0;//将粘在div的顶部
stickyDiv.style.top=stickyValue+'px';
document.getElementById('wrapper').addEventListener('scroll',function(){
var distance=stickyDiv.getBoundingClientRect().top;

if(distance)不存在此类伪类。您是否知道
position:sticky
是一种实验性API,不应在生产中使用?(请参阅)它还没有完全支持并集成到所有浏览器中。请参阅了解浏览器兼容性和支持您如何知道是什么意思?通过查看类?通过查看它是否具有位置粘性?伪类与它有什么关系?当元素粘贴到顶部。因此我认为很难检测到它。您可以尝试使用window.scrollY value或getBoundingClientRect()。元素的顶部。@UncaughtTypeError很好,我知道关于
位置:sticky
兼容性的一切。显然,如果我使用它,我没有理由担心“与旧浏览器的兼容性”。在旧浏览器中出现的最糟糕的事情是元素将有它的初始位置。我对它很满意,谢谢。很好-我想我还是要指出这一点。有时这些事情并不是不言而喻的。似乎现在没有滚动事件就无法解决它。谢谢你的回答!