Alpine 中具有视口边缘的交叉观察器

问题描述 投票:0回答:1

问题

当元素进入视口中间第三个区域时需要执行一个动作:

限制

我正在使用Alpine JS

根据 Alpine intersect docs,我可以使用 .margin 控制底层 IntersectionObserverrootMargin 属性,以更改观察者触发的限制。我的做法如下:

h1 {
margin-top: 95vh;
position: relative;
background-color: blue;
color: white;
z-index: 2;
}

body {
height: 200vh;
}

body::before,
body::after {
content: '';
position: fixed;
left: 0;
right: 0;
height: 33%;
background-color: grey;
z-index: 1;
}

body::before{
top: 0;
}

body::after{
bottom: 0;
}
<html>
<head>
<!-- Alpine Plugins -->
<script defer src="https://unpkg.com/@alpinejs/[email protected]/dist/cdn.min.js"></script>
 
<!-- Alpine Core -->
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
</head>
<body>
    <h1 x-data="{ message: 'Alpine Is Working' }"
    x-intersect:enter.margin.-33%.0.-33%.0="message = 'ENTERED'"
    x-intersect:leave.margin.-33%.0.-33%.0="message = 'LEFT'"
    x-text="message"></h1>
</body>
</html>

在上面的示例中,您可以看到它没有遵守视口的 33% 顶部/底部边距。我使用伪元素将它们标记为灰色。

应该发生什么

在上面的示例中,当元素滚动进出白色区域时,应该显示“已输入”或“向左”。

知道我可能做错了什么吗?

谢谢!

alpine.js intersection-observer
1个回答
0
投票

你的代码在代码片段中对我不起作用,但是当我将其复制到本地 html 文件并在那里运行时,它就起作用了。

iframe 扰乱了交叉口观察者的根。

你的代码对我很有用,我找不到结合 :enter 和 :leave 修饰符的示例。

(由于积分不足,我不得不将其写为答案而不是评论。)

© www.soinside.com 2019 - 2024. All rights reserved.