Javascript 将其转换为jQuery插件
有人能帮我把这个代码变成一个插件吗 我希望能够向进入窗口视图的元素添加类名。我的剧本就是这么做的Javascript 将其转换为jQuery插件,javascript,jquery,plugins,Javascript,Jquery,Plugins,有人能帮我把这个代码变成一个插件吗 我希望能够向进入窗口视图的元素添加类名。我的剧本就是这么做的 var isScrolledIntoView = function(element) { var windowTop = $(window).scrollTop(); var windowBottom = windowTop + $(window).height(); var elementTop = $(element).offset().top; var elementBot
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");
var isScrolledIntoView=函数(元素){
var windowTop=$(window.scrollTop();
var windowBottom=windowTop+$(window).height();
var elementTop=$(element).offset().top;
var elementBottom=elementTop+$(element).height();
如果((元素底部=窗口顶部)){
返回true;
}
};
var showButtonImation=函数(元素,类名){
$(窗口).on(“滚动”,函数(){
if(isScrolledIntoView(元素)){
$(元素).addClass(类名);
}否则{
$(元素).removeClass(类名);
}
});
};
ShowButtonImation(“.button”,“in”);
这里有一个插件,用于您的代码。jquery页面对于学习如何制作插件非常有用
(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");
(函数($){
var isScrolledIntoView=函数($element){
var windowTop=$(window.scrollTop();
var windowBottom=windowTop+$(window).height();
var elementTop=$element.offset().top;
var elementBottom=elementTop+$element.height();
返回(elementBottom=windowTop);
};
$.fn.addClassOnScrollVisible=函数(类名称){
var$collection=this;//插件作用的jQuery集
$(窗口).on(“滚动”,函数(){
//循环集合中的每个元素
$collection.each(函数(){
var$element=$(此);
if(isScrolledIntoView($element)){
$element.addClass(类名);
}否则{
$element.removeClass(类名);
}
});
});
return$collection;//返回输入集合
};
}(jQuery));
//用法示例:
$(“.button”).addClassOnScrollVisible(“in”);
谢谢!这非常有效,帮助我理解如何创建插件。