文档章节

jQuery custom content scroller

lgscofield
 lgscofield
发布于 2015/06/26 13:58
字数 2520
阅读 30
收藏 0
点赞 0
评论 0

基于 jQuery 实现的非常精致的自定义内容滑动条。

Custom scrollbar plugin utilizing jquery UI that’s fully customizable with CSS. Features vertical/horizontal scrolling, mouse-wheel support (via Brandon Aaron jquery mouse-wheel plugin), scroll inertia & easing, auto-adjustable scrollbar length, scroll-to functionality and scrolling buttons.

How to use it

Download the archive which contains all plugin files and examples. Extract files and upload jquery.mCustomScrollbar.js,jquery.mousewheel.min.jsjquery.mCustomScrollbar.css and mCSB_buttons.png to your web server.

Include jquery.mCustomScrollbar.css inside the head tag your html document

 

<link href="jquery.mCustomScrollbar.css" rel="stylesheet" type="text/css" />

 

Include jquery, jquery UI, jquery.mousewheel.min.js and jquery.mCustomScrollbar.js in your html document

 

No wrap HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="jquery.mousewheel.min.js"></script>
<script src="jquery.mCustomScrollbar.js"></script>

 

The code above can be inserted inside the head tag or at the very bottom of your document, before the closing body tag (which is normally recommended for better performance). In either case, it’s more efficient to include css files before any javascript (usually inside the head tag). We’re using Google’s CDN to get jquery and jquery UI libraries (why?). The archive contains copies of both jquery and jquery UI (I’ve made a custom build of jquery UI to decrease its size to 43kb) in case you wanna load them from your own server or locally. You can find both files inside jquery directory.

The way I recommend and what I’ve used in all demos and examples is to load both jquery and jquery UI from Google and have local copies to fallback in case Google files cannot load:

 

No wrap HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="jquery/jquery-1.7.2.min.js"%3E%3C/script%3E'))</script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>!window.jQuery.ui && document.write(unescape('%3Cscript src="jquery/jquery-ui-1.8.21.custom.min.js"%3E%3C/script%3E'))</script>

 

What these files do

jquery is the javascript library used by the plugin (in case you don’t know what jquery is, here it is).

jquery UI (jQuery User Interface) extends jquery library and provides animation easing and drag functionality for our scrollbar.

jquery.mousewheel.min.js is a great 2kb plugin by Brandon Aaron that adds mouse-wheel support for all OS and browsers.

jquery.mCustomScrollbar.js is our main plugin file. The archive contains an additional minified version (jquery.mCustomScrollbar.min.js) which you can find inside the minified directory and is reduced to 16kb.

jquery.mCustomScrollbar.css is the css file we use to style our scrollbar(s) and contains the default styling. You could of course put scrollbars styling in your main stylesheet document to reduce http requests.

The mCSB_buttons.png is a single png image file that contains the default plus some additional sets for the up, down, left and right arrows used by the the scroll buttons. I’ve created a single file in order to use CSS sprites for the buttons (defined in jquery.mCustomScrollbar.css). The archive also contains the PSD source (sources/mCSB_buttons.psd) so you can add your own.

After files inclusion, you call mCustomScrollbar function on the element you want to add custom scrollbars. You can place the following code either in the head or body tag (depending on which tag you included the plugin files). The example below adds scrollbars to all elements with class name “content”:

 

No wrap Javascript
<script>
    (function($){
        $(window).load(function(){
            $(".content").mCustomScrollbar();
        });
    })(jQuery);
</script>

 

Note that we’re wrapping our jquery code with (function($){ ... })(jQuery);. This ensures no conflict between jquery and other libraries using $ shortcut. See Using jQuery with Other Libraries for more info. We also call our function on window load ($(window).load()) so the code executes after all page elements are fully loaded, ensuring the script calculates correctly content’s length. If the scrollbars apply to content that has no elements with external sources (e.g. images, objects etc.) you can use document ready instead (code executes after the DOM is ready):

 

No wrap Javascript
<script>
    (function($){
        $(document).ready(function(){
            $(".content").mCustomScrollbar();
        });
    })(jQuery);
</script>

 

You can change the function call selector (".content") to anything you want (an id, class name, js variable etc.) – see CSS selectors. For instance, if you want custom scrollbars to apply to the element with id “content-1″, you simply do:

 

$("#content-1").mCustomScrollbar();

 

You can also have multiple selectors by inserting comma separated values. For example, the following applies to a)every element with class name “content”, b)every div with rel attribute value with-custom-scrollbar and c)the element with id “content-1″:

 

$(".content,div[rel='with-custom-scrollbar'],#content-1").mCustomScrollbar();

 

The code above will add the default custom scrollbars with the same options parameters to all 3 selectors. Additionally, you can call mCustomScrollbar multiple times within a page for different options (configuration and option parameters explained below) on each selector:

 

No wrap Javascript
<script>
  (function($){
    $(window).load(function(){
      $(".content").mCustomScrollbar();
      $("div[rel='with-custom-scrollbar']").mCustomScrollbar({
        autoDraggerLength:false
      });
      $("#content-1").mCustomScrollbar({
        mouseWheel:false,
        scrollButtons:{
          enable:true
        }
      });
    });
  })(jQuery);
</script>

 

That’s the basics for implementing the plugin. The code below is a most basic html example with a full page markup:

 

No wrap HTML
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body{background:#333; color:#ddd;}
      .content{width:250px; height:450px; overflow:auto;}
    </style>
    <!-- Custom scrollbars CSS -->
    <link href="jquery.mCustomScrollbar.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div class="content">
      <!-- your long content here... -->
    </div>
    <!-- Get Google CDN's jQuery and jQuery UI with fallback to local -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <script>!window.jQuery && document.write(unescape('%3Cscript src="jquery/jquery-1.7.2.min.js"%3E%3C/script%3E'))</script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
    <script>!window.jQuery.ui && document.write(unescape('%3Cscript src="jquery/jquery-ui-1.8.21.custom.min.js"%3E%3C/script%3E'))</script>
    <!-- mousewheel plugin -->
    <script src="jquery.mousewheel.min.js"></script>
    <!-- custom scrollbars plugin -->
    <script src="jquery.mCustomScrollbar.js"></script>
    <script>
      (function($){
        $(window).load(function(){
          $(".content").mCustomScrollbar();
        });
      })(jQuery);
    </script>
  </body>
</html>

 

The plugin will add all necessary markup for the scrollbars to each of your content blocks. The final markup of each content block after being processed by the plugin script, will be:

 

No wrap HTML
<div class="content mCustomScrollbar _mCS_1">
  <div class="mCustomScrollBox">
    <div class="mCSB_container">
      <!-- your long content here... -->
    </div>
    <div class="mCSB_scrollTools">
      <a class="mCSB_buttonUp"></a>
      <div class="mCSB_draggerContainer">
        <div class="mCSB_dragger ui-draggable">
          <div class="mCSB_dragger_bar"></div>
        </div>
        <div class="mCSB_draggerRail"></div>
      </div>
      <a class="mCSB_buttonDown"></a>
    </div>
  </div>
</div>

 

mCSB_buttonUp and mCSB_buttonDown anchors are added only in case you enable scroll buttons (see configuration). The markup for content blocks with horizontal scrollbars is:

 

No wrap HTML
<div class="content mCustomScrollbar _mCS_1">
  <div class="mCustomScrollBox mCSB_horizontal">
    <div class="mCSB_container">
      <!-- your long content here... -->
    </div>
    <div class="mCSB_scrollTools">
      <a class="mCSB_buttonLeft"></a>
      <div class="mCSB_draggerContainer">
        <div class="mCSB_dragger ui-draggable">
          <div class="mCSB_dragger_bar"></div>
        </div>
        <div class="mCSB_draggerRail"></div>
      </div>
      <a class="mCSB_buttonRight"></a>
    </div>
  </div>
</div>

 

All your content resides inside .mCSB_container div. Content blocks with horizontal scrollbars simply get an additional .mCSB_horizontal class name and the button anchors change to mCSB_buttonLeft and mCSB_buttonRight.

Configuration

mCustomScrollbar function can get the following option parameters in order to customize scrollbar behavior and functionality:

set_width: false
Set the width of your content, value in pixels (integer) or percentage (string)
set_height: false
Set the height of your content, value in pixels (integer) or percentage (string)
horizontalScroll: Boolean
Add horizontal scrollbar (default is vertical), values: truefalse
scrollInertia: Integer
Scrolling inertia, value in milliseconds (0 for no scrolling inertia)
scrollEasing: String
Scrolling easing type, see jquery UI easing for all available easing types
mouseWheel: "auto"
Mouse-wheel support, values: truefalse"auto"integer 
By default, mouseWheel is set to “auto” which lowers mousewheel velocity on Safari browser on OSX. To disable mouse wheel set to false or set your own velocity by inserting an integer value (default is 8)
autoDraggerLength: Boolean
Auto-adjust scrollbar dragger length according to content, values: truefalse
scrollButtons:{
    enable: Boolean
}
Scroll buttons support, values: truefalse
scrollButtons:{
    scrollType: String
}
Scroll buttons scroll type, values: "continuous" (scroll continuously while pressing button), "pixels" (scroll by number of pixels on each click) 
See both scroll types in action
scrollButtons:{
    scrollSpeed: Integer
}
Scroll buttons continuous scrolling speed (default: 20), set a higher value for faster scrolling
scrollButtons:{
    scrollAmount: Integer
}
Scroll buttons pixels scroll amount (default: 40), value in pixels
advanced:{
    updateOnBrowserResize: Boolean
}
Update scrollbars on browser resize (for fluid containers & layouts based on percentages), values: truefalse. Set to false only if your content block has fixed dimensions
advanced:{
    updateOnContentResize: Boolean
}
Auto-update scrollbars on content resize (for dynamic content), values: truefalse 
Setting this to true will constantly check for content length changes and update scrollbars accordingly. I recommend to avoid setting this to true if possible, as it causes extra overhead (especially with many scrollbars on a single page). Instead, you can use the update method of the plugin (methods explained below), to update scrollbars manually when needed.
advanced:{
    autoExpandHorizontalScroll: Boolean
}
Auto-expand width for horizontal scrolling, values: truefalse 
Set to true if you have horizontal scrollbar on content that will update dynamically. Demo contains blocks with images and horizontal scrollbars that use this option parameter.
callbacks:{
    onScroll: function(){}
}
User custom callback function to run on scroll event. Run your own function(s) each time a scroll event completes. Example: 
callbacks:{
  onScroll:function(){
    alert("scrolled...");
  }
}
callbacks:{
    onTotalScroll: function(){}
}
User custom callback function to run on scroll end reached event. Example: 
callbacks:{
  onTotalScroll:function(){
    alert("scrolled to end of content.");
  }
}
callbacks:{
    onTotalScrollOffset: Integer
}
Scroll end reached offset, value in pixels 
Demo includes callbacks example. You can also see a more advanced callback example here

Example of defining all options parameters and their default values:

 

No wrap Javascript
$(".content").mCustomScrollbar({
  set_width:false, 
  set_height:false, 
  horizontalScroll:false, 
  scrollInertia:550, 
  scrollEasing:"easeOutCirc", 
  mouseWheel:"auto", 
  autoDraggerLength:true, 
  scrollButtons:{ 
    enable:false, 
    scrollType:"continuous", 
    scrollSpeed:20, 
    scrollAmount:40 
  },
  advanced:{
    updateOnBrowserResize:true, 
    updateOnContentResize:false, 
    autoExpandHorizontalScroll:false 
  },
  callbacks:{
    onScroll:function(){}, 
    onTotalScroll:function(){}, 
    onTotalScrollOffset:0 
  }
});

 

Plugin methods

update

Usage: $(selector).mCustomScrollbar("update");

Call the update method of mCustomScrollbar function to update existing scrollbars each time content changes dynamically (e.g. adding or removing elements with javascript, inserting new content via ajax, hiding/showing content blocks etc.). Methods apply on content blocks that already have custom scrollbars attached. Examples of calling update method:

 

No wrap Javascript
$(".content .mCSB_container").append("<p>New content here...</p>");
$(".content").mCustomScrollbar("update");

 

 

No wrap Javascript
$(".content .myImagesContainer").append("<img src='myNewImage.jpg' />");
$(".content .myImagesContainer img").load(function(){
  $(".content").mCustomScrollbar("update");
});

 

 

No wrap Javascript
$("#content-1").animate({height:800},"slow",function(){
  $(this).mCustomScrollbar("update");
});

 

Always call the update method after newly added content is fully loaded and animations are completed.

scrollTo

Usage: $(selector).mCustomScrollbar("scrollTo",position);

You can auto-scroll to any position within your content by calling the scrollTo method of mCustomScrollbar function. The position can be a string (e.g. “#element-id”, “bottom” etc.) or an integer for scrolling to pixels number. For example, the following will scroll to the last element within your content:

 

$(".content").mCustomScrollbar("scrollTo","last");

 

scrollTo method parameters:

$(selector).mCustomScrollbar("scrollTo",String);
Scrolls to element position, string value can be any unique id, class etc.
$(selector).mCustomScrollbar("scrollTo","top");
Scrolls to top (vertical scrollbars)
$(selector).mCustomScrollbar("scrollTo","bottom");
Scrolls to bottom (vertical scrollbars)
$(selector).mCustomScrollbar("scrollTo","left");
Scrolls to left-end (horizontal scrollbars)
$(selector).mCustomScrollbar("scrollTo","right");
Scrolls to right-end (horizontal scrollbars)
$(selector).mCustomScrollbar("scrollTo","first");
Scrolls to the first element position within the content
$(selector).mCustomScrollbar("scrollTo","last");
Scrolls to the last element position within the content
$(selector).mCustomScrollbar("scrollTo",Integer);
Scrolls to number of pixels, e.g. $(selector).mCustomScrollbar("scrollTo",200);

scrollTo method has 2 additional option parameters:

moveDragger: Boolean
Scroll scrollbar dragger (instead of content) to number of pixels, values: truefalse. Example: 
$(selector).mCustomScrollbar("scrollTo",200,{
  moveDragger:true
});
callback: Boolean
Run callbacks after scroll-to completes, values: truefalse. Example: 
$(selector).mCustomScrollbar("scrollTo",200,{
  callback:true
});

Styling the scrollbars

Style your scrollbar(s) using the jquery.mCustomScrollbar.css file which contains the default style. You can directly change the default styling or you can keep it and add additional styles for each scrollbar (check the stylesheet inside demo_files that I’ve used to style the scrollbars for the demo and examples).

You can have separate styling for each of your scrollbars on the same page, either by giving your content blocks different class names or ids or simply by targeting them in your css like this:

 

No wrap CSS
._mCS_1 .mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{
    /* 1st scrollbar dragger style... */
}
._mCS_2 .mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{
    /* 2nd scrollbar dragger style... */
}
._mCS_3 .mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{
    /* 3rd scrollbar dragger style... */
}

 

…and so on. Each content block in your document that has custom scrollbars gets automatically an additional unique class in the form of _mCS_+index number (e.g. _mCS_1) based on its index number within the DOM. This way you can easily target and style any scrollbar using its parent class name.

Custom scrollbar layout

Additional info

Scrolling content that’s over 9999 pixels with older versions of jQuery

There’s a jQuery bug (prior to version 1.5) that resets to 0, an animate value greater than 9999 pixels. This bug will affect the scrollbar if your content’s width or height is greater than 9999 pixels and you use jQuery version of 1.4 and below, resulting a scrolling jerk (scrolling resets to 0 after pixels limit reached). This annoying bug is fixed on version 1.5 of the library. If you do use an older version, there’s a quick solution that overwrites the jquery function containing the buggy code ;) Insert the following code outside the window load or document ready functions:

 

No wrap Javascript
<script>
/* function to fix the -10000 pixel limit of jquery.animate */
$.fx.prototype.cur = function(){
    if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
      return this.elem[ this.prop ];
    }
    var r = parseFloat( jQuery.css( this.elem, this.prop ) );
    return typeof r == 'undefined' ? 0 : r;
}
</script>

 

Loading & updating content dynamically

Each time you programmatically change the contents of a content block with custom scrollbars, you need to call plugin’s updatemethod (see methods section) in order to update its scrollbar according to the newly added content. You should always call theupdate method after dynamic content is fully loaded (see an ajax example).

There’s an option parameter (advanced:{ updateOnContentResize: true }) that automatically calls the update method if content length is changed so you don’t have to do it manually. I do not recommend setting this to true unless absolutely necessary, as it adds unnecessary overhead (especially if you have many scrollbars on a page).

Hiding & showing content blocks with custom scrollbars

Hidden content blocks have zero dimensions, so calling mCustomScrollbar function on them will not work. Instead, you should call the function after your blocks are fully visible, so the plugin calculates content length correctly and apply/update the scrollbar (see an example).

When hiding-showing content blocks with custom scrollbars, always call the update method after animations are completed and content is fully visible.

Touch devices

The plugin checks for touch devices and applies overflow: auto css rules, as well as -webkit-overflow-scrolling: touch to the content block so it can be scrolled natively by swiping (tested on iOS 5.1 on iPad, Android 2.xx).

本文转载自:http://lgscofield.iteye.com/blog/1679525

共有 人打赏支持
lgscofield

lgscofield

粉丝 20
博文 140
码字总数 63036
作品 0
南京
架构师
20个最有创意最实用的jQuery应用

我们看看三年来,这个被成为最优雅的Javascript框架带来那些创意应用。 以下翻译自国外网站,示例网站如无法点击访问,请自觉翻墙~ 原文链接:http://nettuts.com/articles/web-roundups/th...

晨曦之光
2012/03/09
0
0
5月最新超有趣的免费jQuery插件推荐

本文再给大家介绍一些比较有趣的,jQuery 插件。 1) Wow Window - 可用于替换 Lightbox,更有趣而且功能更强大。使用CSS3,这点不太好,没法兼容所有浏览器。 2) jQuery News Ticker - 新闻的...

任洪君
2011/12/22
0
0
jQuery命名冲突解决的五种方案

引言: 最近遇到个问题,同时引用了jquery库和另外一个js库。当用$XX去调用js库函数时,发现失效了!于是找资料,原来是jquery命名冲突了。因为许多JavaScript 库使用$作为函数或变量名,jqu...

龙上
2012/03/30
0
0
2014年140个最好的jQuery插件集合

Material Design Preloader Want to create a Google’s latest Material Design look-alike pre-loader? If yes, this jQuery plugin created by Aaron Lumsden will help you do so and y......

IanSun
2015/03/14
0
0
使用原生的 javascript 来替代 jquery

JSON JQUERY $.getJSON('/my/url', function(data) { }); IE9+ var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onload = function() { if (request.st......

蜗牛奔跑
2015/07/01
0
0
jQuery对象与DOM对象的相互转换

下面介绍jquery对象和DOM对象的相互转换: 在使用jquery框架进行处理时,当我们使用$(expression)方法时,如:获取id="jquery_a"的div元素对象时,实际上获取到的值不是DOM对象,而是jquery对...

Sandy_wu
2013/03/27
0
1
jquery-nicescroll 的使用

Nicescroll is a jquery plugin, for nice scrollbars with a very similar ios/mobile style. NOW support HORIZONAL scrollbar too! It supports DIVs, IFrames, textarea, and document p......

大叔做web前端
2014/04/28
0
1
Zepto.js简介(第二章)

接着上章的继续记录。 zepto 特点: 1、体积8kb 2、针对移动端的框架 3、语法同jquery大部分一样,都是$为核心函数 4、目前功能完善的框架体积最小的左右 zepto同jquery不同的API attr同pro...

张靖bibibi
06/22
0
0
jquery的一些用法 有用的用法。

AJAX 框架 用Asp.net ajax 还是 Jquery? AJAX 流行之后,总想好好学习一下。但是众多的框架实在难以选择。说明一下 ASP.NETAJAX 并不包括在 AJAX 框架之中。 刚开始学了 JQuqery,众多的 $g...

雪中漫步
2010/03/29
0
0
19个 jQuery 分页插件和教程,附带实例

在这篇文章中我们将向你介绍 20 个最棒的 jQuery 分页插件以及教程,并提供在线演示。 1.客户端的jQuery 分页插件jPages jPages 是一个客户端的分页插件,但提供很多特性例如自动翻页、键盘和...

凯文加内特
2014/04/30
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

4 个快速的 Python 编译器 for 2018

简评:Python 和其他的解释型语言一样经常被吐槽性能不行,所以开发人员为了提升性能创建了不少编译器,本文则选取其中的四个做了基准测试。 Python 其实是一种相当快的语言,但它并不像编译...

极光推送
6分钟前
0
0
SSO CAS单点登录搭建详细步骤及源码

1.因为是本地模拟sso环境,而sso的环境测试需要域名,所以需要虚拟几个域名出来,步骤如下: 2.进入目录C:\Windows\System32\drivers\etc 3.修改hosts文件 127.0.0.1 jeesz.cn 127.0.0.1 sso...

明理萝
7分钟前
0
1
spring boot注册多个MQ服务器的问题

关于注册到多个MQ源的文章已经有很多了,这里记录一下声明queue的坑; 如果使用注册bean的方式声明queue,会导致声明的queue同时被注册到所有的MQ源上; //如果使用下面的声明方式,que...

placeholder
7分钟前
0
0
Java面试基础篇——第九篇:BIO,NIO,AIO的区别

现在IO模型主要分三类:BIO(同步阻塞IO),NIO(同步非阻塞IO),AIO()。 先来看看BIO。 1. BIO 服务端接受到请求后,要指派或新建一个线程去处理客户端的IO请求,直到收到断开连接的指令。这么做...

developlee的潇洒人生
12分钟前
0
0
@RequestMapping @ResponseBody 和 @RequestBody 用法与区别

1.@RequestMapping 国际惯例先介绍什么是@RequestMapping,@RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为...

特拉仔
14分钟前
1
0
基于 HTML5 结合互联网+ 的 3D 隧道

前言 目前,物资采购和人力成本是隧道业发展的两大瓶颈。比如依靠民间借贷,融资成本很高;采购价格不透明,没有增值税发票;还有项目管控和供应链管理的问题。成本在不断上升,利润在不断下...

xhload3d
16分钟前
0
0
济南小程序热度分析

原文链接:http://www.jnqianle.cn/company/2072.html

tianma3798
17分钟前
1
0
大数据软件

beats 采集 kafka spark hive es grafana zeppelin

ArlenXu
19分钟前
0
0
Mac item2常用快捷键

标签 新建标签:command + t 关闭标签:command + w 切换标签:command + 数字 command + 左右方向键 切换全屏:command + enter 查找:command + f 分屏 水平分屏:command + d 垂直分屏:c...

说回答
23分钟前
0
0
mac常用软件

1.excel for mac http://www.pc6.com/mac/114205.html

小黑202
23分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部