簡體   English   中英

jQuery根據頁面滾動添加/刪除類

[英]jQuery Adding/Removing class according to page scroll

我有一個代碼段,當用戶向下滾動網頁時,在我的網站上使用該代碼段顯示號召性用語btn。 但是它不能在我的一個網站上工作。 我已經研究過,找不到錯誤。 這是我正在使用此代碼的頁面鏈接 為什么JS不在元素中添加“ atcbottomactive”類?

  $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= 1100) { $(".atcbottom").addClass("atcbottomactive"); } else { $(".atcbottom").removeClass("atcbottomactive"); } }); 
 @media only screen and (min-width:1000px) { .atcbottom { display: none!important } .btnn { margin-top: -60px!important } } @media only screen and (max-width:999px) { .atcbottomactivepopup { margin-bottom: 60px } } .atcbottom { height: 60px; width: 100vw; position: fixed; z-index: 102; background: #fff; bottom: -100px; transition: 2s; left: 0; } .atcbtn { height: 40px; background: #4cae4c; width: 90vw; margin-top: 10px; margin-left: 5vw; border: none; color: #fff; font-size: 20px; } .atcbottomactive { bottom: 0 } 
 <div style="height:1000px; width: 100%; background: blue"> <div class='atcbottom'> <div class="container"> <div class="row"> <a href="#ProductPrice-product-template"> <button type="button" class="atcbtn">Call to action</button> </a> </div> </div> </div> </div> 

當我查看您的網站並打開開發人員控制台時,看到以下錯誤:

在此處輸入圖片說明

看來jQuery在您的網站上可用,但是由於某種原因未保存到$變量中。 您必須使用jQuery變量進行訪問。

我看了看您的網站,在開發人員控制台中說它沒有調整$符號。 您可以將$符號更改為jQuery。 但是如果要使用$符號,則需要加載jquery的slim.min版本。

您可以使用純Javascript做到這一點,這是我為您編寫的示例。 希望我的代碼有用!

 window.addEventListener("scroll", function(e){ e=(e||window.event); e.preventDefault(); const topOffset=window.scrollY; document.querySelector("#scrollOffset").innerHTML="ScrollTop: "+topOffset+"px"; if(topOffset> 100 ){ document.querySelector(".box").classList.add("scrollEffect"); }else document.querySelector(".box").classList.remove("scrollEffect"); }); 
 span#scrollOffset{ position: fixed; left: 50%; top: 10px; transform: translateX(-50%); padding: 4px 8px; padding-top: 6px; border-radius: 4px; background-color: rgba(0,0,0,.5); z-index: 10; color: white; font-size: 12px; font-family: Arial, sans-serif; } .box{ width: 200px; height: 200px; background-color: #eee; padding: 20px; } .box.scrollEffect{ background-color: yellow; } 
 <body style="min-height: 200vh"> <span id="scrollOffset">ScrollTop: 0px</span><br> <div class="box">This box class must change when scroll even fires !</div> <body> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM