javascript - 转换函数以将其用作 "on"事件

标签 javascript jquery

我目前有这个功能:

function isInView() {
  var windowStart = $(window).scrollTop();
  var windowEnd = windowStart + $(window).height();

  $('.box').each(function() {
    var box = $(this);
    var start = box.offset().top;
    var end = start + box.height();

    if (windowStart <= start && windowEnd >= end) {
      box.addClass('active');
    } else {
      box.removeClass('active');
    }
  });
}

$(document).scroll(isInView);

此函数检查整个元素在视口(viewport) ( jsfiddle ) 中是否可见,并从元素中添加/删除 active 类。

但是,我希望能够将此函数用作“on”事件,以便我可以应用于许多不同的元素。这意味着以某种方式转换函数并为其分配自己的事件自定义,例如 isinview

换句话说,我希望能够像这样使用它:

$('.box').on('isinview', function () {
    if (elementIsInView) {
        // make the box red
    } else {
        // make the box the original color
    }
});

或者对于不同的元素:

$('.nav').on('isinview', function () {
    if (elementIsInView) {
        // make the nav bigger
    } else {
        // make the nav the original height
    }
});

我该怎么做?

最佳答案

您可以将其重写为插件,并触发事件

$.fn.isInView = function() {
  var self = this;
  $(window).on('scroll resize', function() {
    var windowStart = $(window).scrollTop();
    var windowEnd   = windowStart + $(window).height();

    self.each(function() {
      var box   = $(this);
      var start = box.offset().top;
      var end   = start + box.height();

      if (windowStart <= start && windowEnd >= end) {
        if (!box.data('inview')) box.trigger('isinview').data('inview', true);
      } else {
        if (box.data('inview') ) box.trigger('hasleftview').data('inview', false);
      }
    });
  }).trigger('scroll');
  return self;
}

$('.box')
  .on('isinview', function() {
    $(this).addClass('active');
}).on('hasleftview', function() {
    $(this).removeClass('active');
}).isInView(); // call plugin after events are bound
body {
  margin: 50px;
}
.container {
  width: 300px;
  background: lightgrey;
  padding: 50px;
}
.box {
  display: block;
  width: 100%;
  height: 300px;
  background: grey;
}
.box:not(:last-of-type) {
  margin-bottom: 50px;
}
.box.active {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

关于javascript - 转换函数以将其用作 "on"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40695748/

相关文章:

javascript - React JS 映射对象名称的问题

javascript - MeteorJS + Bower 并指定加载顺序

javascript - 过滤分页传递参数到异步 ember 数据关系请求

javascript - localStorage onload 显示我选择的 div?

javascript - 如何在CSS中使用位置?

javascript - 函数不在 jquery 文档就绪时执行

jquery - 2016年没有Jquery UI的JS表格行拖拽

javascript - 如何在不在服务器上创建页面的情况下将字符串解释为 HTML 页面

javascript - 透明 PNG 响应网站图像 slider 和内容

jquery.mention 默认文本