【问题标题】:Turning this into a jQuery Plugin把它变成一个 jQuery 插件
【发布时间】:2017-09-21 16:31:46
【问题描述】:

有人可以帮我把这段代码变成plugin吗?

https://codepen.io/spz457/pen/NaNddP

我希望能够为进入窗口视图的元素添加类名。这就是我的脚本所做的。

var isScrolledIntoView = function(element) {
  var windowTop = $(window).scrollTop();
  var windowBottom = windowTop + $(window).height();
  var elementTop = $(element).offset().top; 
  var elementBottom = elementTop + $(element).height();

  if ((elementBottom <= windowBottom) && (elementTop >= windowTop)) {
    return true; 
  } 
};

var showButtonAnimation = function(element, className) {
  $(window).on("scroll", function() {
    if (isScrolledIntoView(element)) {
      $(element).addClass(className);
    } else {
      $(element).removeClass(className);
    }
  });
};

showButtonAnimation(".button", "in");

【问题讨论】:

    标签: javascript jquery plugins


    【解决方案1】:

    这是您的代码的插件。 jquery How to Create a Basic Plugin 页面对于学习如何制作插件非常有用。

    (function($) {
    
        var isScrolledIntoView = function($element) {
            var windowTop = $(window).scrollTop();
            var windowBottom = windowTop + $(window).height();
            var elementTop = $element.offset().top; 
            var elementBottom = elementTop + $element.height();
    
            return (elementBottom <= windowBottom) && (elementTop >= windowTop);
        };
    
        $.fn.addClassOnScrollVisible = function(className) {
            var $collection = this;     // the jQuery set the plugin is acting on
    
            $(window).on("scroll", function() {
    
                // loop over each element in the collection
                $collection.each(function() {
                    var $element = $(this);
    
                    if (isScrolledIntoView($element)) {
                      $element.addClass(className);
                    } else {
                      $element.removeClass(className);
                    }
                });
            });
    
            return $collection;     // return the input collection
        };
    
    }(jQuery));
    
    // Usage example:
    $(".button").addClassOnScrollVisible("in");
    

    【讨论】:

    • 谢谢!这很好用,可以帮助我了解如何创建插件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多