繁体   English   中英

使用javascript使另一个元素消失后,如何使一个元素消失。 滚动触发?

[英]How to make one element disappear after you made another one appear using javascript. triggered by scrolling?

我有一个元素内的文本,当您向下滚动时,该文本会出现在标题中。

但是,我还想同时使页面的第一部分消失。 所以我将javascript设置在同一滚动点。 这是一个小功能,我不想依赖任何库。 因此,请仅提供简单的javascript解决方案建议。

的HTML

<header class="header-home">
  <div>
    Company
  </div>
  <span class="header-copy">
    is so awesome
  </span>

  <button></button>  
</header>

<!-- test content -->
<section class="landing-bg">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
</section> 

Java脚本

我从最上面的代码块开始,当滚动300px时,所有代码都能正常工作以使header-copy的文本显示出来。

var span = document.querySelectorAll('.header-home .header-copy')[0];

span.style.display = "none";

document.addEventListener("scroll", function() {
  if (document.body.scrollTop > 300) {
    span.style.display = "inline-block";
  }
  else {
    span.style.display = "none";
  }
});

但是后来我想使页面的第一部分消失。

/* makes the top content go away */

var content = document.getElementsByClassName("landing-bg")[0];

content.style.display = "block";

document.addEventListener("scroll", function() {
  if (document.body.scrollTop > 300) {
    content.style.display = "none";
  }
  else {
    content.style.display = "block";
  }
});

完整的演示可在CodePen获得

我最终嵌套了代码并验证了类名。 回答这个问题,而不是删除,以防万一有人可以使用此代码作为示例。

Java脚本

/* Allows you to select a class within a class */
var span = document.querySelectorAll('.header-home .header-copy')[0];
span.style.display = "none";

/* you can select an element with a specific class*/
var content = document.getElementsByClassName("landing-bg")[0];
content.style.display = "block";

document.addEventListener("scroll", function() {
  /* edit to the scroll point that you need */
  if (document.body.scrollTop > 300) {
    span.style.display = "inline-block";
    content.style.display = "none";
  }
  else {
    content.style.display = "block";
    span.style.display = "none";
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM