简体   繁体   English

在 Vanilla JS 的滚动问题上添加 Class

[英]Add Class on Scroll Issue with Vanilla JS

I am coding a new site for a client and I want to add a class to a div element once the user reaches 100vh.我正在为客户编写一个新站点,一旦用户达到 100vh,我想将 class 添加到 div 元素。 I have given the body an id of "myBody" and the div element that I want to add the class to an id of "quoteForm" and a class of "quote-form" Here is the html of the page...我已经给body一个ID“myBody”和我想将class添加到“quoteForm”的ID和“quote-form”的class的div元素这是ZFC35FDC70D5FC679D269EZ883A页面...

<body id="myBody">
  <div id="quoteForm" class="quote-form">
    <div id="quoteFormHead"></div>
    <form action="<?php the_permalink(); ?>" method="post">
      <div id="quoteFormBody">
        <div class="formfullwrapper">
          <input type="text" name="message_fname" placeholder="Enter your full name here...">
        </div>
        <div class="formfullwrapper">
          <input type="email" name="message_email" placeholder="Enter your email address here...">
        </div>
        <div class="formfullwrapper">
          <input type="number" name="message_phone" placeholder="Enter your phone number here...">
        </div>
        <div class="formfullwrapper">
          <textarea name="message_msg" placeholder="Details, please! Audience? Word count? Type of document? Tone? Deadlines? Sensitive content?"></textarea>
        </div>
      </div>
      <div id="quoteFormFooter">
        <div class="formfullwrapper">
          <input type="submit" id="submitform" value="Get my free quote">
        </div>
      </div>
    </form>
  </div>
</body>

as you can see its quite a simple form.如您所见,它是一个非常简单的形式。 Below if the javascript logic I have used to add the class name...下面如果 javascript 逻辑我用来添加 class 名称...

document.addEventListener("DOMContentLoaded", function(){
  var scrollElement = document.getElementById('myBody');
  var scrollElementPos = scrollElement.scrollTop;
  var form = document.getElementById('quoteForm');

  scrollElement.addEventListener('scroll', function(){
    scrollElementPos = scrollElement.scrollTop;
    if(scrollElementPos >= 10){
      form.classList.add("form-fixed");
    } else {
      form.classList.remove("form-fixed");
    }
    console.log(scrollElementPos);
  });
});

At present nothing is happening and the class name is not being added to the quote form.目前没有任何事情发生,并且 class 名称未添加到报价单中。 Any ideas?有任何想法吗? Many thanks,非常感谢,

Phillip Dews菲利普·杜斯

Yep its the scroll "On" Window.是的,它的卷轴“打开”Window。 This is what I came up with and it works a dream...这就是我想出的,它是一个梦想......

window.onscroll = function(){
  var top = window.pageYOffset || document.documentElement.scrollTop;
  var form = document.getElementById('quoteForm');
  if (top > 1000) {
    form.classList.add("form-fixed");
  } else {
    form.classList.remove("form-fixed");
  }
}

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

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