2011-03-11 7 views
0

표준 API 기능을 넘어서서 JQuery에서 너무 익숙하지는 않지만 내 페이지에는 동일한 코드를 사용하는 많은 수의 스크롤러가 있습니다. 각기 다른 몇 가지 고유 한 설정이 있습니다. (예 : 분리 높이 및 스크롤 한계 및 스크롤 된 현재 횟수). 나는 코드를 반복적으로 사용할 수 있기를 원하지만, 각 참조는 자체 변수 세트를 받는다. 저는 프로토 타입이 제가 생각한 것입니다,하지만 저는 이것에 대해 본 적이있는 예제를 머리에 새겨 넣을 수는 없습니다. 그래서 기본적으로 내가 원하는 것 무엇일반적으로 사용되는 함수에 대한 jquery 프로토 타입

$(document).ready(function() { 
     var scrollAmt = 50; //distance in pixels; 
     var scrollableAmt = $('#weblinks .container').outerHeight(); 
     var viewAmt = $('#weblinks').outerHeight(); 

     var maxScroll = Math.ceil((scrollableAmt-viewAmt)/scrollAmt); 
     var currentItem = 0; 

     function setScrollButtons(scrollRef,scrollAmount){ 

     } 

     $("#weblinks .scrollDownBtn").click(function(){ 
      if (currentItem <= maxScroll){ 


       $('#weblinks .container:not(:animated)').animate({'top' : '-='+ scrollAmt + ''},500,function(){ 
        currentItem++ 
       }); 

      } else { 
       currentItem = 0; 
       $('#weblinks .container:not(:animated)').animate({'top' : currentItem},500); 
      } 
     }); 
     $("#weblinks .scrollUpBtn").click(function(){ 
      if (currentItem > 0){ 

       $('#weblinks .container:not(:animated)').animate({'top' : '+='+ scrollAmt + ''},500,function(){ 
        currentItem--; 
       }); 

      } else { 
       $('#weblinks .container:not(:animated)').animate({'top' : currentItem},500); 
      } 
     }); 
    }); 

위의 코드를 모두 수행하는 함수 또는 클래스, 내 생각을 만들지 만에 그것을 사업부 기준을 통과 할 수있다 : 이것은 내 스크롤 코드 #weblinks를 대신 사용하고 스크롤 량을 전달하면이 기능의 여러 인스턴스가 같은 페이지에 함께 존재할 수 있습니다. 누구든지 이것에 대해 가장 좋은 방법에 대해 조언을합니까?

편집 : 각 스크롤러에 대해 항상 존재하는 HTML을 추가했습니다.

<div id="weblinks" class="scrollbar_container"> 
     <div class="customScrollBox"> 
      <div class="container"> 
       <div class="content"> 

       </div> 
      </div> 

      <a class="scrollUpBtn" href="javascript:void(0);"></a> <a class="scrollDownBtn" href="javascript:void(0);"></a>   
     </div> 
    </div> 
+0

어쩌면 HTML의 데모를 보여줄 수 있습니까? 상수는 무엇입니까? (예를 들어 항상'.container','.scrollDownBtn' &'.scrollUpBtn'?) –

+0

확실합니다 - 저는 이것을 추가했습니다 - 상수는 모든 HTML이 될 것입니다. scrollableAmt, viewAmt 및 maxScroll입니다. – mheavers

+0

@ mheavers : 스크롤바 사이에 달라지기를 원하는 조정 가능한 값은 무엇입니까? (어떤 매개 변수에서 일반적으로이 "Addon"에 전달할 것인가? _ scrollbar A_ 대 * scrollbar B_?) –

답변

1

내 입찰가 :

(function($){ 
    $.fn.extend({ 
     customScroller: function(options){ 
      return this.each(function(i,e){ 
       var container = $(e).find('.container'), 
        content = $(e).find('.content'), 
        scrollUpBtn = $(e).find('.scrollUpBtn'), 
        scrollDownBtn = $(e).find('.scrollDownBtn'); 

       var self = $(e); 
       var o = $.extend({}, $.fn.customScroller.defaults, options); 

       o.scrollableAmt = container.outerHeight(); 
       o.viewAmt = self.outerHeight(); 
       o.maxScroll = Math.ceil((o.scrollableAmt - o.viewAmt)/o.scrollAmt); 

       scrollDownBtn.click(function(){ 
        console.log('DOWN -- current: '+o.currentItem); 
        if (o.currentItem <= o.maxScroll){ 
         container.filter(':not(:animated)').animate({ 
          top: '-='+o.scrollAmt 
         },500,function(){ 
          o.currentItem++; 
         }); 
        }else{ 
         o.currentItem = 0; 
         container.filter(':not(:animated)').animate({ 
          top: o.currentItem 
         },500); 
        } 
       }); 
       scrollUpBtn.click(function(){ 
        console.log('UP -- current: '+o.currentItem); 
        if (o.currentItem > 0){ 
         container.filter(':not(:animated)').animate({ 
          top: '+='+o.scrollAmt 
         },500,function(){ 
          o.currentItem--; 
         }); 
        }else{ 
         container.filter(':not(:animated)').animate({ 
          top: o.currentItem 
         },500); 
        } 
       }); 
      }); 
     } 
    }); 

    $.fn.customScroller.defaults = { 
     scrollAmt: 50, 
     scrollableAmt: 0, 
     viewAmt: 0, 
     maxScroll: 0, 
     currentItem: 0 
    }; 
})(jQuery); 

$('#weblinks').customScroller(); 

나는 귀하의 질문에 대답하려면 두 옵션을 확장하고 다른 옵션은 jQuery addon 기능을 사용합니다.

  • $.fn.extend이 기능을 확장하고 있습니다.
  • $.extend({},$.fn.customScroller.defaults, option);을 사용하면 .customScroller({ scrollAmount: 10 })으로 전화를 걸고 스크롤 동작을 변경할 수 있습니다.

기타 문의 사항은 질문 해주십시오.

1

모든 div의 하위 컨테이너 클래스가있는 경우 매우 간단하게 리팩토링 할 수 있습니다. 같은 뭔가 : 당신이 약간 다른 것 개체에 대한 실제 레퍼런스를 가지고 있다면

$(document).ready(function() { 
    scrollExample('#webLinks'); 
} 

,하지만 여전히 비슷한 원리를 따르

function scrollExample(divId) { 
    var scrollAmt = 50; //distance in pixels; 
    var scrollableAmt = $(divId + ' .container').outerHeight(); 
    var viewAmt = $(divId).outerHeight(); 

    var maxScroll = Math.ceil((scrollableAmt-viewAmt)/scrollAmt); 
    var currentItem = 0; 

    function setScrollButtons(scrollRef,scrollAmount){ 

    } 

    $(divId + " .scrollDownBtn").click(function(){ 
     if (currentItem <= maxScroll){ 


      $(divId + ' .container:not(:animated)').animate({'top' : '-='+ scrollAmt + ''},500,function(){ 
       currentItem++ 
      }); 

     } else { 
      currentItem = 0; 
      $(divId + ' .container:not(:animated)').animate({'top' : currentItem},500); 
     } 
    }); 
    $(divId + " .scrollUpBtn").click(function(){ 
     if (currentItem > 0){ 

      $(divId + ' .container:not(:animated)').animate({'top' : '+='+ scrollAmt + ''},500,function(){ 
       currentItem--; 
      }); 

     } else { 
      $(divId + ' .container:not(:animated)').animate({'top' : currentItem},500); 
     } 
    }); 
}); 

는 다음과 같은 무언가를 호출합니다.

+0

필자가 볼 수있는 유일한 문제는 사람들이 여러 스크롤러와 상호 작용하여 하나의 스크롤러에서 currentItem이 3이고 다른 하나는 스크롤러가 될 수 있기 때문에 currentItem과 같은 변수를 버릴 수 있다는 것입니다. 4. 네? – mheavers

+0

아, 그래, 그런 경우 변수에 충돌이있을 수 있습니다. 이상적인 것은 함수를 가져 와서 네임 스페이스를 만드는 것입니다. 함수를 사용할 때마다 올바르게 네임 스페이스를 지정하면 문제가 발생하지 않습니다. 또한 새 인스턴스마다 늘어나는 배열을 유지할 수도 있습니다. – CraigKerstiens

1

이것은 스스로 만들 수있는 jQuery 플러그인을위한 좋은 후보입니다. 물론이 중 일부 내용은이 원리 :

How to develop a jQuery plugin을 시간을 보내고 배우고 싶다면 무엇의 jQuery 플러그인은 어떻게