CSS-如何根据页面中的位置隐藏元素?

发布于 2025-02-04 08:28:15 字数 243 浏览 2 评论 0原文

我在移动设备上设置了一个粘性元素。这是代码:

.sticky-btn {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
}

运行良好,但我不希望按钮显示用户何时在页面的顶部。只有在您向下滚动后出现20-30像素后才出现,这将是完美的。是否可以在CSS中以某种方式完成此操作?

谢谢!

I have a sticky element I've setup for a button on mobile devices. This is the code:

.sticky-btn {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
}

Works great but I don't want the button to show when the user is at the very top of the page. It would be perfect if it only appeared after you scrolled down say 20-30 pixels. Is it possible to accomplish this in CSS somehow?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仅一夜美梦 2025-02-11 08:28:15

布莱恩·普雷斯顿(Brian Preston)。不幸的是,我们不能仅使用CSS来做到这一点。我们应该使用该类javascript将“粘性”类添加到粘性按钮和切换按钮。

.sticky-btn {
  position: fixed;
  bottom: 20px;
  left: 50%;
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
  transform: translateX(-50%);
  transition: all .3s ease-in-out;
}
.sticky-btn.sticky {
  opacity: 1;
  visibility: visible;
  pointer-events: all;
}

JS代码应该是这样。

document.addEventListener('DOMContentLoaded', function () {
    var scrollPosition = window.scrollY;
    var stickyBtn = document.querySelector('.sticky-btn');
    window.addEventListener('scroll', function() {

        scrollPosition = window.scrollY;
    
        if (scrollPosition >= 30) {
            stickyBtn.classList.add('sticky');
        } else {
            stickyBtn.classList.remove('sticky');
        }
    });

});

希望这会有所帮助。愉快的编码〜:)

Brian Preston. Unfortunately, we can't do this using only CSS. We should Javascript to add "sticky" class to sticky button and toggle button using that class.

.sticky-btn {
  position: fixed;
  bottom: 20px;
  left: 50%;
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
  transform: translateX(-50%);
  transition: all .3s ease-in-out;
}
.sticky-btn.sticky {
  opacity: 1;
  visibility: visible;
  pointer-events: all;
}

And JS code should be like this.

document.addEventListener('DOMContentLoaded', function () {
    var scrollPosition = window.scrollY;
    var stickyBtn = document.querySelector('.sticky-btn');
    window.addEventListener('scroll', function() {

        scrollPosition = window.scrollY;
    
        if (scrollPosition >= 30) {
            stickyBtn.classList.add('sticky');
        } else {
            stickyBtn.classList.remove('sticky');
        }
    });

});

Hope this helps. Happy coding ~ :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文