在20%的元素之前添加一个滚动类

时间:2018-02-13 04:37:49

标签: javascript jquery html

我有这个功能,它在滚动到元素时执行,它在视图中,我想编辑它以在20%的元素之前滚动执行。

JS:

#include <iostream>;
using namespace std;

int main() {
    int x = 0; //variable x created
    int cars (14);//cars is created as a variable with value 14
    int debt{ -1000 };//debt created with value 1000
    float cash = 2.32;
    double credit = 32.32;
    char a = 'a';//for char you must use a single quote and not double
    char* sandwich = "ham";
    return 0;
}

HTML:

function isScrolledIntoView(elem) {
  var centerY = Math.max(0, ((jQuery(window).height() - jQuery(elem).outerHeight()) / 2) +
    jQuery(window).scrollTop());
  var elementTop = jQuery(elem).offset().top;
  var elementBottom = elementTop + jQuery(elem).height();
  return elementTop <= centerY && elementBottom >= centerY;
}

jQuery(window).on("scroll resize", function() {
  jQuery(".element)").each(function(index, element) {
    if (isScrolledIntoView(element)) {
      jQuery(element).addClass("newClass");
    }
  });
});

1 个答案:

答案 0 :(得分:2)

您必须计算元素20%的{​​{1}},然后使用height

offset的元素top中减去它

Stack Snippet

&#13;
&#13;
$(this).offset().top
&#13;
jQuery(window).on("scroll resize", function() {
  jQuery(".element").each(function() {
    var percentage = ($(this).outerHeight() * 20) / 100;
    if (jQuery(window).scrollTop() > jQuery(this).offset().top - percentage) {
      jQuery(this).addClass("newClass");
    } else {
      jQuery(this).removeClass("newClass");
    }
  });
});
&#13;
.element {
  height: 200px;
  width: 200px;
  background: red;
  color: #fff;
  margin: 0 auto 30px;
}

body {
  margin: 300px 0;
}

.element.newClass {
  background: green;
}
&#13;
&#13;
&#13;