尝试应用一个脚本,该脚本应在滚动一定数量的px后使浮动按钮出现,但是它不起作用

时间:2020-10-02 19:51:36

标签: javascript

<script>

document.addEventListener
    ('DOMContentLoaded', 
    function() {
jQuery(function($){
$(document).scroll(function() 
    {
var y = $(this).scrollTop();
if (y > 1810 && $(window
    ).scrollTop() + $(window
    ).height() < $(document
    ).height() - 100) {
$('#addcartsection').addClass
    ('viewaddcart')
} else {
$('#addcartsection'
    ).removeClass
    ('viewaddcart')
}
});
$('#addcartbutton').click
    (function(){
$('.single_add_to_cart_button'
    ).click();
$('html, body').animate({
scrollTop: $('.product_title'
    ).offset().top
}, 'slow');
});
});
});
</script>

<style>
#addcartsection{
position: fixed;
bottom: 0;
width: 100vw;
z-index: 98;
-webkit-transition: transform 
    0.34s ease;
transition : transform 0.34s
    ease;
transform: translateY(0px); /*adjust this value to the height of your addcartsection*/
}
.viewaddcart{
transform: translateY(0px
    )!important;
}
</style>

将其应用于页面构建器html元素中,但该按钮始终显示,而不是在页面上向下滚动一定数量的px后出现。脚本中是否有任何错误?抱歉,我不是编码专家。

1 个答案:

答案 0 :(得分:0)

似乎可以正常工作,请确保您默认情况下将其隐藏,并且仅在同一按钮上存在viewaddcart类时显示:

#addcartsection {
  ...
  display: none;
}

#addcartsection.viewaddcart {
  display: block;
}

document.addEventListener('DOMContentLoaded',
  function() {
    jQuery(function($) {
      $(document).scroll(function() {
        var y = $(this).scrollTop();
        if (y > 1810 && $(window).scrollTop() + $(window).height() < $(document).height() - 100) {
          $('#addcartsection').addClass('viewaddcart')
        } else {
          $('#addcartsection').removeClass('viewaddcart')
        }
      });
      $('#addcartbutton').click(function() {
        $('.single_add_to_cart_button').click();
        $('html, body').animate({
          scrollTop: $('.product_title').offset().top
        }, 'slow');
      });
    });
  });
#addcartsection {
  position: fixed;
  bottom: 0;
  width: 100vw;
  z-index: 98;
  -webkit-transition: transform 0.34s ease;
  transition: transform 0.34s ease;
  transform: translateY(0px);
  /*adjust this value to the height of your addcartsection*/
}

.viewaddcart {
  transform: translateY(0px)!important;
}

.veryHugeDocument {
  background: grey;
  height: 5000px;
}

#addcartsection {
  width: 100px;
  color: white;
  background: blue;
  right: 0;
  display: none;
}

#addcartsection.viewaddcart {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="veryHugeDocument">
  <h1>My document!</h1>
</div>
<button id="addcartsection">Add to cart!</button>