Scroll bar plug-in mcustomscrollbar

Source: Internet
Author: User
Tags jquery library

The system's default scroll bar style is really disgusting. Imagine how awkward it would be if a system's default scroll bar style appears on a very distinctive and creative web page. I have been looking for a long time to define the scroll bar method on my webpage. As for the results I have found, I have found two good jquery plug-ins: jscrollpane and mcustomscrollbar. You may have seen a lot about the former, but this plug-in is too old and not powerful. The results were good a few years ago, but it is hard to say it now. So I chose the latter: mcustomscrollbar. Is a simple comparison of the two official examples:

 

This article describes how to use this plug-in. Most of the content is translated based on the official introduction page of mcustomscrollbar, but some of its content is modified and some tips are added.

About mcustomscrollbar

Mcustomscrollbar uses jquery UI, which allows you to flexibly define your scroll bar through CSS. Vertical and horizontal scroll bars can be defined at the same time, and the support for mouse scrolling is provided through Brandon Aaron jquery mouse-wheel plugin, you can also cache and scroll to make the scrolling smoother. You can automatically adjust the position of the scroll bar and define the scroll position. In short, you know it is very easy to use.

 

How to Use mcustomscrollbar

First, download the plug-in package provided by the author, which contains all plug-in files and some examples. The following four files must be uploaded to your server: jquery. mcustomscrollbar. JS, jquery. mousewheel. Min. JS, jquery.mcustomscrollbar.css and mcsb_buttons.png.

Step 1: load the style file of the plug-in.

You can use the following code to introduce the jquery.mcustomscrollbar.css style table file in the plug-in package.

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

Step 2: load necessary JS files.

The files to be loaded include jquery, jquery UI, jquery. mousewheel. Min. JS, and jquery. mcustomscrollbar. js. Jquery and jquery UI are required. jquery. mousewheel. Min. JS is used to provide rolling support. jquery. mcustomscrollbar. JS is the main file of the plug-in. It should be noted that the loading sequence should also follow the above description. If you do not pay attention to the loading sequence, it may cause failure. For the reason, please refer to your own: the order of code in a webpage is a detail that cannot be ignored.

You can use the following code to load:

<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>

You can put this code at the bottom of the document to shorten the loading time of webpage content. The reason can also be seen in the article described above. The loaded code here uses Google's CDN acceleration service to obtain jquery and jquery UI, which has advantages and disadvantages. The plug-in package contains jquery and jquery UI (this UI is simplified by the author and contains the modules required by this plug-in. The size is only 43kb ), of course, you can upload the two libraries in the plug-in package to the server for use. They are in the jquery directory of the plug-in package.

If you are using a CDN service similar to a common JavaScript library of Google or Sina, we recommend that you use the following method (take Google as an example ):

<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>

If it is written in this way, it will make a judgment after the library is loaded: if the library is not loaded successfully, a new JavaScript reference code will be generated to reference local files. In this way, if the external library cannot be used, the local library will be loaded without the plug-in being unusable. This method is recommended.

Step 3: Activate the plug-in for the content Block

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

Here I used (function ($ ){... }) (Jquery); To wrap jquery code to avoid conflicts between jquery and other libraries. I also used window load ($ (window ). load () to activate the plug-in function, because in this way, you can ensure that after all the page objects are loaded, load my plug-in. Of course, you can also use the regular jquery code loading method, but you need to understand the differences between ready and load methods. The general jquery code loading method is as follows:

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

Step 4: add content and styles to the page

If there is no content, the effect of this plug-in cannot be discussed. For the above sample code, we should define a content block with class as content on the page. And add some test data:

<div class=".content">    <p>测试数据.......还有很多很多</p></div>

Of course, this is not the end. to customize the scroll bar style, you must have a scroll bar. So we need to add some CSS to this block to display the scroll bar, otherwise it will not work. The style is simple, that is, to define either the width or the height or the width and height, and then define an overflow value as auto. In this way, if the content exceeds the specified width and height, a scroll bar will appear. Example:

width:100px;height:100px;overflow:auto;

After completing the above operations, the scroll bar of the content block with the scroll bar will become the default style of this plug-in.

 

The official default style is not high in contrast to the white one, so I added a dark background color to make it clearer.

Of course, there are many parameters to enable the extension plug-in function. The usage of these parameters will be discussed later. Let's talk about the usage and brief introduction of the files used above:

Jquery: A required library for this plug-in, you know.

Jquery UI: extends the jquery library and provides simple animation and drag functions for our scroll bars.

Jquery. mousewheel. Min. JS: this is a great 2kb plug-in compiled by Brandon Aaron. It targets all operating systems and browsers and provides support for mouse scroll events.

Jquery. mcustomscrollbar. JS: This is the main file of our plug-in. You can find its compressed version in the minified of the plug-in package.

Jquery.mcustomscrollbar.css: This CSS file is used to define the sidebar. You can define your sidebar in this file. Of course, you can define it in other CSS files. Note that you must use the sequence in CSS, the priority relationship overwrites the definition in this file. Otherwise, the code sequence in the webpage may be invalid. For details, refer to this article: the code sequence in the webpage cannot be ignored.

Mcsb_buttons.png: This PNG image file contains buttons that scroll up to the left to the right. You can use the corresponding buttons in the image by using the CSS Sprites technology. The plug-in package contains the PSD source file (sources/mcsb_buttons.psd) for this image. You can customize it as needed.

After completing these steps, you can use the plug-in correctly and see the corresponding effect. However, no one is willing to use such a powerful plug-in to achieve this default effect. Next, let's look at the Advanced use.

Introduction to mcustomscrollbar Parameters

This plug-in has a huge number of functions, so there are many parameters, of course, more parameter values. When introducing parameters, I would like to introduce the writing methods of two parameter values for beginners, which are directly and merged.

Parameters Used by the plug-ins we usually use are directly followed by parameter values, which is intuitive and simple. In this plug-in, there are too many parameter values, so some parameters are merged and written. For example, the scrollbuttons parameter to be introduced below has four attributes: Enable, scrolltype, scrollspeed, and scrollamount. These four attributes also have their own values to implement corresponding functions. If other parameters are added, we should write as follows:

$("#main").mCustomScrollbar({ scrollButtons:{ enable:false, scrollType:"continuous", scrollSpeed:20, scrollAmount:40 }, horizontalScroll:false, });

Be sure to note the comma between Closed parentheses and statements. New users may fail to run the plug-in because they are not careful and do not strictly follow this rule. Okay. The following describes the detailed parameters.

  • Set_width: false | set the width of your content to pixel or percentage.
  • Set_height: false | set the height of your content to pixel or percentage.
  • Horizontalscroll: Boolean | whether to create a horizontal scroll bar. By default, the vertical scroll bar value can be: true (create a horizontal scroll bar) or false.
  • Scrollinertia: integer | the rolling inertia value can be zero in milliseconds (the rolling inertia can make the block rolling smoother)
  • Scrolleasing: String | scroll action type. View jquery UI easing. All types are displayed.
  • Mousewheel: String/Boolean | supported values for mouse scroll: True. False. By default, the mouse scroll value is set to false to cancel the mouse scroll function.
  • Mousewheelpixels: integer | the number of pixels that scroll in the mouse scroll. The value is a value in pixels.
  • Autodraggerlength: Boolean | automatically adjusts the length of the scroll bar drag Block Based on the content area. Values: true and false
  • Scrollbuttons: {enable: Boolean} | whether to add buttons on both sides of the scroll bar. Supported values: true and false
  • Scrollbuttons: {scrolltype: string} | scroll type value of the scroll button: "continuous" (if you click the scroll control button, it will be intermittently rolled) "pixels" (based on the number of hits each time)
  • Scrollbuttons: {scrollspeed: integer} | set the scroll speed when you click the scroll button (20 by default). Set a higher value to scroll faster.
  • Scrollbuttons: {scrollamount: integer} | sets the default unit of value pixels for each scroll when the scroll button is clicked. The default unit is 40 pixels.
  • Advanced: {updateonbrowserresize: Boolean} | adjust the size of the scroll bar in the browser based on the percentage. Values: true and false. Set this parameter to false. If your content block has been fixed
  • Advanced: {updateoncontentresize: Boolean} | automatically adjusts the size of the scroll bar based on the dynamically changed content: True, setting false to true will continuously check the length of the content and change the size of the scroll bar accordingly. It is recommended that you do not set it to true unless necessary. If there are many scroll bars on the page, it may cause extra removal. you can use the update method to replace this function.
  • Advanced: {autoexpandhorizontalscroll: Boolean} | the length of the horizontal scroll bar is automatically expanded to true, and false to true. You can adjust the size automatically based on the dynamic changes in the content.
  • Advanced: {autoscrollonfocus: Boolean} | whether to automatically scroll to an object in the focus. For example, if a form uses a tab key to jump to the focus value: True False
  • Callbacks: {onscrollstart: function () {}} | run the custom callback function at the start of the rolling time.
  • Callbacks: {onscroll: function () {}} | the demo of the custom callback function in the scrolling process is the same as the demo.
  • Callbacks: {ontotalscroll: function () {}} | call this custom callback function demo when scrolling to the bottom. Same as above
  • Callbacks: {ontotalscrollback: function () {}} | call this UDF demo when you scroll to the top of the page.
  • Callbacks: {ontotalscroloffset: integer} | sets the offset pixel unit to reach the top or bottom.
  • Callbacks: {whilescrolling: function () {}} | the custom callback function is executed when the user is rolling.
  • Callbacks: {whilescrollinginterval: integer} | sets the interval (in milliseconds) for calling the whilescrolling callback function.

The following is a list of all parameters and their default values.

$(".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,    autoScrollOnFocus:true  },  callbacks:{    onScrollStart:function(){},    onScroll:function(){},    onTotalScroll:function(){},    onTotalScrollBack:function(){},    onTotalScrollOffset:0,    whileScrolling:false,    whileScrollingInterval:30  }
Update the mcustomscrollbar Method

Usage: $ (selector). mcustomscrollbar ("Update ");

Call the update method of the mcustomscrollbar function to update the scroll bar in real time when the content changes (for example, adding or removing an object through JavaScript, inserting a new content through Ajax, hiding or displaying a new content)

The following is an example:

$(".content .mCSB_container").append("<p>New content here...</p>");$(".content").mCustomScrollbar("update");
$(".content .myImagesContainer").append("
$("#content-1").animate({height:800},"slow",function(){  $(this).mCustomScrollbar("update");});

After the new content is fully loaded or the animation is complete, the update method is always called.

Scrollto

Usage: $ (selector). mcustomscrollbar ("scrollto", position );

You can use this method to automatically scroll to the position you want to scroll. You can use a string (for example, "# element-ID" or "bottom") to describe this position or a value (in pixel units ). The following example will scroll to the bottom object

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

Scrollto method parameters

    • $ (Selector). mcustomscrollbar ("scrollto", string); | scroll to the position of an object. The string value can be the ID or class name.
    • $ (Selector). mcustomscrollbar ("scrollto", "top"); | scroll to the top (vertical scroll bar)
    • $ (Selector). mcustomscrollbar ("scrollto", "bottom"); | scroll to the bottom (vertical scroll bar)
    • $ (Selector). mcustomscrollbar ("scrollto", "left"); | scroll to the leftmost (horizontal scroll bar)
    • $ (Selector). mcustomscrollbar ("scrollto", "right"); | scroll to the rightmost (horizontal scroll bar
    • $ (Selector). mcustomscrollbar ("scrollto", "First"); | scroll to the first object location in the content area
    • $ (Selector). mcustomscrollbar ("scrollto", "last"); | scroll to the last object location in the content area
    • $ (Selector). mcustomscrollbar ("scrollto", integer); | scroll to a certain position (pixel unit)

The scrollto method has two additional option parameters.

Movedragger: Boolean | the unit of pixels from the slider of the scroll bar to a certain position. Value: True, flase. Example: $ (selector). mcustomscrollbar ("scrollto", 200, {movedragger: true });

Callback: Boolean | run the callback function. After scroll-to is completed, the value is true, and false indicates $ (selector ). mcustomscrollbar ("scrollto", 200, {callback: true });

Disable

Usage: $ (selector). mcustomscrollbar ("disable ");

Call the disable method to make the scroll bar unavailable. To make it available again, call the update method. The Disable method uses an optional parameter (the default value is false). You can set true if you want to re-scroll the content area when the scrollbar is unavailable. For example:

$(".content").mCustomScrollbar("disable",true);
Destroy

Usage: $ (selector). mcustomscrollbar ("destroy ");

Call the destroy method to remove the custom scroll bar of an object and restore the default style.

How mcustomscrollbar works

Through the use of these plug-ins, The provisioner m also analyzes the implementation principles of these plug-ins. The principle is as follows:

First, obtain the content block of the scroll bar style to be modified, and then use CSS to hide the default scroll bar. Then, use JavaScript to add a lot of HTML structures, and then use CSS to make a scroll bar effect. Then, use CSS to define the scroll bar style, and use the scroll event of the corresponding JavaScript mouse to produce the scroll down effect.

After understanding this, let's take a look at the structure of the scroll bar and use CSS to define it.

Define the scroll bar appearance

First, let's take a look at the HTML structure of the scroll bar. below is the default vertical scroll bar structure:

<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>

The mcsb_buttonup and mcsb_buttondown labels are available only when scroll buttons is enabled. The following structure is the structure of the horizontal scroll bar:

<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>

After knowing this, we can define the scroll bar style. For Multiple scroll bars on the same page, the official recommendation is as follows:

._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... */}

In order to more intuitively see the scroll bar area to be defined, the official team provides a very vivid image.

Based on this image, you can easily define the style of the scroll bar.

More advanced use of modifying the browser's scroll bar

Simply modifying the sidebar of a content area cannot meet our needs. What should we do if we want to modify the browser sidebar? Of course, this cannot be implemented using JavaScript, because the browser is a container and JavaScript is the code in the container. How can we modify the container? Of course, if there is a problem, there must be a solution. To solve this problem, a browser window is virtualized.

We first add a div block, then add the position: absolute attribute to the DIV, and then we can specify its width and height as 100% or a slightly smaller 98%. In this way, the DIV is expanded to the entire browser interface, which can be regarded as the body of a webpage. Add overflow: auto to make it exceed the threshold and the scroll bar appears automatically. In this way, you can simulate the effect of modifying the browser scroll bar.

Scroll bar plug-in mcustomscrollbar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.