使用Javascript在移动视图中滚动时固定在页面上的按钮

Button fixed to page when scrolling in mobile view with Javascript

本文关键字:按钮 移动 Javascript 视图 滚动 使用      更新时间:2023-09-26

希望在这里得到一些JS/CSS的帮助。我需要在我的页面上的结帐按钮去页面的顶部,成为固定的,如果用户不能再看到它在移动视图下滚动页面。我希望有人能帮忙!唯一让我困惑的是我不能使用jQuery

![function checkoutScroll() {
    var button = document.querySelector('.cartSidebar__checkoutButton');
    window.addEventListener('scroll', function () {
      var distanceFromTop = document.body.scrollTop;
      if (distanceFromTop === 0) {
        button.style.position = 'static';
        button.style.top = 'auto';
      }
      if (distanceFromTop > 0) {
        button.style.position = 'fixed';
        button.style.top = '0px';
      }
    });
  }

你想要实现的可以通过CSS来完成,这将更有意义,因为它是一个视觉/UI任务。我将添加顶边距相当于你的按钮的css高度,并保留它作为固定的顶部。作为一个好处,您将能够利用媒体查询来限制CSS规则的移动视图。

@media screen and (max-width: 960px) {
    .container{
        margin: 3em;
    }
    .checkout_button{
        display:block;
        position:fixed;
        top:0;
        left:0;
        width:100%;
    }
}

一些非常简单的东西,比如https://jsfiddle.net/f19Lus43/

如果你想留在javascript一些模糊的原因(我不能说兼容性,因为文件。querySelector只在进化的浏览器上工作),这取决于你,但有一个例子,你的代码将帮助我们回应:)

所以我认为你想要的功能只运行在较小的屏幕/浏览器视图?这就是你所说的"移动视图"吗?我已经用了一段时间了。不确定它是否比格伦的解决方案更好,但它对我有效,没有任何错误。首先定义函数:

function updateViewportDimensions() {
    var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.clientHeight;
    return { width:x,height:y };
}
// setting the viewport width
var viewport = updateViewportDimensions();
function detectMob() {
  viewport = updateViewportDimensions();
  if (viewport.width <= 768) {
    return true;
  } else {
   return false;
  }
}

然后每次你需要检查视口的大小是否小于768像素宽,你做:

if (detectMob){
  //your code here
}