jQuery slimScroll

werkraft

Создатель
Регистрация
11 Мар 2010
Сообщения
32
Реакции
1
Здравствуйте, вот нашел хорошей плагин, и решил переделать его под свои нужды и возможности. Но так как в этом деле я новичок то не совсем все получилось.Помогите сделать так чтоб можно было скроллить по всему блоку где подключен скролл.

И ещё один нюанс там подключался jQuery UI для перетаскивания ползунка, я посчитал, что больно большая библиотека для использования только ради одной функции (Для тех у кого нет возможности или хотения использовать jQuery UI ).

Помогите оптимизировать код и довести до нормального состояния.

Заранее спасибо!

Код:
(function($) {

  jQuery.fn.extend({
    slimScroll: function(options) {

      var defaults = {
	  
	    clPref : 'scroll_',

        // height in pixels of the visible scroll area
        height : 'auto',

        // scrollbar position - left/right
        position : 'right',

        // distance in pixels between the side edge and the scrollbar
        distance : '1px',

        // default scroll position on load - top / bottom / $('selector')
        start : 'top',

        // enables always-on mode for the scrollbar
        alwaysVisible : false,

        // check if we should hide the scrollbar when user is hovering over
        disableFadeOut: false,

        // sets visibility of the rail
        railVisible : true,

        // whether  we should use jQuery UI Draggable to enable bar dragging
        railDraggable : true,

        // defautlt CSS class of the slimscroll rail
        railClass : 'scrollbar_cont',

        // defautlt CSS class of the slimscroll bar
        barClass : 'scrollbar_inner',

        // check if mousewheel should scroll the window if we reach top/bottom
        allowPageScroll : false,

        // scroll amount applied to each mouse wheel step
        wheelStep : 12,

        // scroll amount applied when user is using gestures
        touchScrollStep : 100
      };

      var o = $.extend(defaults, options);

      // do it for every element that matches selector
      this.each(function(){

      var isOverPanel, isOverBar, isDragg, queueHide, touchDif,
        barHeight, percentScroll, lastScroll,
        divS = '<div></div>',
        minBarHeight = 40,
        releaseScroll = false;

        // used in event handlers and for better minification
        var me = $(this);

        // ensure we are not binding it again
       if (me.parent().hasClass(this))
        {
            // start from last bar position
            var offset = me.scrollTop();

            // find bar and rail
            bar = me.parent().find('.' + o.clPref + o.barClass);
            rail = me.parent().find('.' + o.clPref + o.railClass);

            getBarHeight();
            // check if we should scroll existing instance
            if ($.isPlainObject(options))
            {
              // Pass height: auto to an existing slimscroll object to force a resize after contents have changed
              if ( 'height' in options && options.height == 'auto' ) {
                me.parent().css('height', 'auto');
                me.css('height', 'auto');
                var height = me.parent().height();
                me.parent().css('height', height);
                me.css('height', height);
              }

              if ('scrollTo' in options)
              {
                // jump to a static point
                offset = parseInt(o.scrollTo);
              }
              else if ('scrollBy' in options)
              {
                // jump by value pixels
                offset += parseInt(o.scrollBy);
              }
              else if ('destroy' in options)
              {
                // remove slimscroll elements
                bar.remove();
                rail.remove();
                me.unwrap();
                return;
              }
              // scroll content by the given offset
              scrollContent(offset, false, true);
            }
            return;
        }

        // optionally set height to the parent's height
        o.height = (o.height == 'auto') ? me.height() : o.height;

        // update style for the div
        me.css({
            position: 'relative',
            overflow: 'hidden',
            height: o.height
        });

        // create scrollbar rail
        var rail = $(divS)
          .addClass(o.clPref + o.railClass)
          .css({
            height: o.height,
            display: (/*o.alwaysVisible &&*/ o.railVisible) ? 'block' : 'none',
          });

        // create scrollbar
        var bar = $(divS)
          .addClass(o.clPref + o.barClass)
          .css({
            display: o.alwaysVisible ? 'block' : 'none',			
		    top: 2
          });

        // set position
		rail.css( (o.position == 'right') ? { right: o.distance, left: 'auto' } : { right: 'auto', left: o.distance });
        
        // append to parent div
		me.before(rail.append(bar));

        // make it draggable		
		function dontStartSelect() {
			return false;
		}
		var isClicked = false;
		

		bar.bind("mousedown",  function(e) {
		    rail.addClass('scrollbar_c_overed');		
			clickPointY = e.pageY - $(this).offset().top;
			isClicked = true;
			e.preventDefault();
			$(document).on('selectstart', dontStartSelect);
        });

        $(document).bind("mouseup blur", function(e) {
          if (isClicked) {
		     rail.removeClass('scrollbar_c_overed');
			$(document).off('selectstart', dontStartSelect);
			var selfTop= parseInt(bar.css('top'));
			topY = Math.min(Math.max(2, (selfTop)), me.height() - bar.height());
			bar.css({top: topY});
			scrollContent(0, bar.position().top, false);
          }
          isClicked = false;

        });

        $(document).bind("mousemove", function(e) {
          if (isClicked) {
			topY = Math.min(Math.max(2, (e.pageY - rail.offset().top - clickPointY)), me.height() - bar.height());
            bar.css({top: topY});
			scrollContent(0, bar.position().top, false);
          }
        });

        // on rail over
        rail.hover(function(){
		  if (o.railVisible)
		  rail.addClass('scrollbar_c_overed'); 
        }, function(){
		if(isClicked !== true)
		  rail.removeClass('scrollbar_c_overed');
        });

        // on bar over
        bar.hover(function(){
          isOverBar = true;
        }, function(){
          isOverBar = false;
        });

        // show on parent mouseover
        me.hover(function(){
          isOverPanel = true;
        }, function(){
          isOverPanel = false;
        });

        // support for mobile
        me.bind('touchstart', function(e,b){
          if (e.originalEvent.touches.length)
          {
            // record where touch started
            touchDif = e.originalEvent.touches[0].pageY;
          }
        });

        me.bind('touchmove', function(e){
          // prevent scrolling the page
          e.originalEvent.preventDefault();
          if (e.originalEvent.touches.length)
          {
            // see how far user swiped
            var diff = (touchDif - e.originalEvent.touches[0].pageY) / o.touchScrollStep;
            // scroll content
            scrollContent(diff, true);
          }
        });

        // check start position
        if (o.start === 'bottom')
        {
          // scroll content to bottom
          bar.css({ top: (me.outerHeight() - bar.outerHeight()) });
          scrollContent(0, true);
        }
        else if (o.start !== 'top')
        {
          // assume jQuery selector
          scrollContent($(o.start).position().top, null, true);

          // make sure bar stays hidden
          if (!o.alwaysVisible) {  bar.hide(); }
        }

        // attach scroll events
        attachWheel();

        // set up initial height
        getBarHeight();

        function _onWheel(e)
        {
          // use mouse wheel only when mouse is over
          if (!isOverPanel) { return; }

          var e = e || window.event;

          var delta = 0;
          if (e.wheelDelta) { delta = -e.wheelDelta/120; }
          if (e.detail) { delta = e.detail / 3; }

          var target = e.target || e.srcTarget || e.srcElement;
            // scroll content
            scrollContent(delta, true);

          // stop window scroll
          if (e.preventDefault && !releaseScroll) { e.preventDefault(); }
          if (!releaseScroll) { e.returnValue = false; }
        }

        function scrollContent(y, isWheel, isJump)
        {
          var delta = y;
          var maxTop = me.outerHeight() - bar.outerHeight();

          if (isWheel)
          {
            // move bar with mouse wheel
            delta = parseInt(bar.css('top')) + y * parseInt(o.wheelStep) / 100 * bar.outerHeight();

            // move bar, make sure it doesn't go out
            delta = Math.min(Math.max(delta, 2), maxTop - 2);

            // if scrolling down, make sure a fractional change to the
            // scroll position isn't rounded away when the scrollbar's CSS is set
            // this flooring of delta would happened automatically when
            // bar.css is set below, but we floor here for clarity
            delta = (y > 0) ? Math.ceil(delta) : Math.floor(delta);

            // scroll the scrollbar
            bar.css({ top: delta + 'px' });
          }

          // calculate actual scroll amount
          percentScroll = parseInt(bar.css('top')) / (me.outerHeight() - bar.outerHeight());
          delta = percentScroll * (me[0].scrollHeight - me.outerHeight()+40)-20;

          if (isJump)
          {
            delta = y;
            var offsetTop = delta / me[0].scrollHeight * me.outerHeight();
            offsetTop = Math.min(Math.max(offsetTop, 2), maxTop - 2);
            bar.css({ top: offsetTop + 'px' });
          }

          // scroll content
          me.scrollTop(delta);

          // fire scrolling event
          me.trigger('slimscrolling', ~~delta);

          // ensure bar is visible
          showBar();

          // trigger hide when scroll is stopped
          hideBar();
        }

        function attachWheel()
        {
          if (window.addEventListener)
          {
            this.addEventListener('DOMMouseScroll', _onWheel, false );
            this.addEventListener('mousewheel', _onWheel, false );
			/*this.addEventListener('MozMousePixelScroll', function( event ){
                    event.preventDefault();
                }, false);*/
          }
          else
          {
            document.attachEvent("onmousewheel", _onWheel)
          }
        }

        function getBarHeight()
        {
          // calculate scrollbar height and make sure it is not too small
          barHeight = Math.max(Math.floor((me.outerHeight() / me[0].scrollHeight) * me.outerHeight()), minBarHeight);
          bar.css({ height: barHeight + 'px' });

          // hide scrollbar if content is not long enough
          var display = barHeight == me.outerHeight() ? 'none' : 'block';
          bar.css({ display: display });
        }

        function showBar()
        {
          // recalculate bar height
          getBarHeight();
          clearTimeout(queueHide);

          // when bar reached top or bottom
          if (percentScroll == ~~percentScroll)
          {
            //release wheel
            releaseScroll = o.allowPageScroll;

            // publish approporiate event
            if (lastScroll != percentScroll)
            {
                var msg = (~~percentScroll == 0) ? 'top' : 'bottom';
                me.trigger('slimscroll', msg);
            }
          }
          else
          {
            releaseScroll = false;
          }
          lastScroll = percentScroll;

          // show only when required
          if(barHeight >= me.outerHeight()) {
            //allow window scroll
            releaseScroll = true;
            return;
          }
		 bar.stop(true, true).addClass(o.clPref + 'scrollbar_hovered');
        }

        function hideBar()
        {
          // only hide when options allow it
          if (!o.alwaysVisible)
          {
            queueHide = setTimeout(function(){
              if (!(o.disableFadeOut && isOverPanel) && !isOverBar && !isDragg)
              {
				bar.removeClass(o.clPref + 'scrollbar_hovered');
              }
            }, 300);
          }
        }

      });

      // maintain chainability
      return this;
    }
  });

  jQuery.fn.extend({
    slimscroll: jQuery.fn.slimScroll
  });

})(jQuery);
 
Это понятно, но сам подумай если ты её не используешь зачем ради одной функции подключать?
Эта либа, по сути, набор слабозависимых контролов и эффектов, в итоге получается ядро+слайдер, весит сущие пустяки. Перелопачивать код для отвязки от грузных либ - это, конечно, хорошо в плане оптимизации, но ведь и по времени затратно. Банально того не стоит.
 
Эта либа, по сути, набор слабозависимых контролов и эффектов, в итоге получается ядро+слайдер, весит сущие пустяки. Перелопачивать код для отвязки от грузных либ - это, конечно, хорошо в плане оптимизации, но ведь и по времени затратно. Банально того не стоит.
Я его уже отвязал, и все сделал. Но только не как не могу понять, как сделать чтоб прокручивалось ко всему блоку а не только где выводится контент! Ну и конечна посмотреть на правильность кода!
 
Назад
Сверху