当一个类出现在ViewPort中时,jQuery隐藏 [英] jQuery hide when a class appears in ViewPort

查看:74
本文介绍了当一个类出现在ViewPort中时,jQuery隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当向下滚动时,如果某个类在ViewPort中消失,我想使FIXED按钮消失.

I would like to make a FIXED button dispear when a certain class apears in the ViewPort when scrolling down.

要具体说明其固定的添加到购物车"按钮,当您向下滚动到产品说明下方显示的静态添加到购物车"按钮时,该按钮应会消失.

To be more specific its a fixed Add-To-Cart button, it should disapear when uer scrolls down to the static Add-to-cart button that shows under the products description.

等待帮助,一定很容易,我只是经验不足而已... 谢谢!

Waiting for help, must be easy i'm just not very experienced... Thanks!

推荐答案

新的

The new Intersection Observer API addresses your question very directly.

此解决方案将需要使用polyfill,因为Safari和Opera尚不支持此功能. (该解决方案中包含了polyfill).

This solution will need a polyfill as Safari and Opera don't support this yet. (the polyfill is included in the solution).

在此解决方案中,看不见的框是目标(观察到的).当它出现时,标题顶部的按钮被隐藏.一旦框离开视图,就会显示出来.

In this solution, there is a box out of view that is the target (observed). When it comes into view, the button at the top in the header is hidden. It is shown once the box leaves the view.

以下是解决您的问题的代码:

Here is the code to solve your problem:

const buttonToHide = document.querySelector('button');

const hideWhenBoxInView = new IntersectionObserver((entries) => {
  if (entries[0].intersectionRatio <= 0) { // If not in view
    buttonToHide.style.display = "inherit";
  } else {
    buttonToHide.style.display = "none";
  }
});

hideWhenBoxInView.observe(document.getElementById('box'));

header {
  position: fixed;
  top: 0;
  width: 100vw;
  height: 30px;
  background-color: lightgreen;
}

.wrapper {
  position: relative;
  margin-top: 600px;
}

#box {
  position: relative;
  left: 175px;
  width: 150px;
  height: 135px;
  background-color: lightblue;
  border: 2px solid;
}

<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>
<header>
  <button>NAVIGATION BUTTON TO HIDE</button>
</header>
  <div class="wrapper">
    <div id="box">
    </div>
  </div>

这篇关于当一个类出现在ViewPort中时,jQuery隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆