我需要调试此jQuery的帮助,其中我以固定的大小操作容器中元素的上边距,并且将溢出设置为隐藏,以便可以创建视差效果。视差有效,但是如果您向下滚动甚至一个像素,然后重新加载页面,它都会中断。谁能帮我解决这个问题?这是代码。

//Parallax for Header
$(window).on("load", function() {
    var startingScrollTop = parseInt($(window).scrollTop());
    console.log(startingScrollTop);
    var startingElementTop = parseInt($headerText.css("margin-top"));
    console.log(startingElementTop);
    $(window).on("scroll", function() {
        var currentScrollTop = parseInt($(window).scrollTop());
        console.log(currentScrollTop);
        if(currentScrollTop > startingScrollTop) {
            var scrollDistance = currentScrollTop - startingScrollTop;
            console.log(scrollDistance);
            var parallaxDistance = scrollDistance / 2;
            console.log(parallaxDistance);
            var newElementMarginTop = startingElementTop + parallaxDistance;
            console.log(newElementMarginTop);
            $headerText.css("margin-top", newElementMarginTop + "px");
        } else if(currentScrollTop <= "0") {
            $headerText.css("margin-top", "0px");
        }
    });
});


感谢您的帮助。

最佳答案

我知道了,但是如何简化呢?

//Parallax for Header
$(window).on("load", function() {
  var startingScrollTop = 0;
  console.log(startingScrollTop);
  var startingElementTop = parseInt($headerText.css("margin-top"));
  console.log(startingElementTop);
  //Re-use this on scroll
  var currentScrollTop = parseInt($(window).scrollTop());
  console.log(currentScrollTop);
  if(currentScrollTop > startingScrollTop) {
    var scrollDistance = currentScrollTop - startingScrollTop;
    console.log(scrollDistance);
    var parallaxDistance = scrollDistance / 2;
    console.log(parallaxDistance);
    var newElementMarginTop = startingElementTop + parallaxDistance;
    console.log(newElementMarginTop);
    $headerText.css("margin-top", newElementMarginTop + "px");
  } else if(currentScrollTop <= "0") {
    $headerText.css("margin-top", "0px");
  }
  //Put the re-used code here
  $(window).on("scroll", function() {
    var currentScrollTop = parseInt($(window).scrollTop());
    console.log(currentScrollTop);
    if(currentScrollTop > startingScrollTop) {
      var scrollDistance = currentScrollTop - startingScrollTop;
      console.log(scrollDistance);
      var parallaxDistance = scrollDistance / 2;
      console.log(parallaxDistance);
      var newElementMarginTop = startingElementTop + parallaxDistance;
      console.log(newElementMarginTop);
      $headerText.css("margin-top", newElementMarginTop + "px");
    } else if(currentScrollTop <= "0") {
      $headerText.css("margin-top", "0px");
    }
  });
});


我可以将重用的代码转换成可以在加载,滚动或任何其他处理程序上运行的函数吗?

关于javascript - 简单的jQuery视差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23614824/

10-12 15:49