Jquery自定义滚动条插件

一直想整理jquery相关的插件来着,却一直没有行动,借这次机会整理下,顺便分享给大家

相关html代码:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 2     
 3 <html>
 4     <head>
 5         <title>jScrollPane - basic examples</title>
 6         <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 7         <link rel="stylesheet" type="text/css" media="all" href="/css/demoStyles.css" />
 8         <link rel="stylesheet" type="text/css" media="all" href="/css/jScrollPane.css" />
 9         <script type="text/javascript" src="/Scripts/jquery-1.4.1.min.js"></script>
10         <script type="text/javascript" src="/Scripts/jquery.mousewheel.js"></script>
11         <script type="text/javascript" src="/Scripts/jScrollPane.js"></script>
12         <script type="text/javascript">
13 
14             $(function () {
15                 $('#pane1').jScrollPane();
16             });
17             
18         </script>
19     </head>
20     <body>
21         <h1>jScrollPane</h1>
22         <h2>Basic examples</h2>
23         <p id="intro">
24             These simple examples show how you can use <a href="jScrollPane.html">jScrollPane</a> to replace your
25             browser's default scrollbars on an element with overflow:auto. You can see
26             how you can easily control the appearance of the scrollbars using basic
27             CSS. View source to see how it's all done...
28         </p>
29         
30         <div class="holder">
31             <h3>#pane1</h3>
32             <div id="pane1" class="scroll-pane">
33                 <p>>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec condimentum pretium nisl. Integer quis tellus nec turpis placerat scelerisque. In semper lacus eu nisi. Praesent dignissim metus sit amet enim. Nam auctor, neque semper congue sagittis, risus mi commodo pede, nec euismod magna libero at sem. In enim magna, vestibulum et, blandit sit amet, tempor vel, ligula. Phasellus ante augue, congue vitae, faucibus quis, gravida sit amet, diam. Nullam congue accumsan magna. Etiam a nunc. Aliquam elit urna, ornare vitae, ultrices et, tempus non, nisl. Duis eros neque, luctus quis, interdum ultricies, auctor eu, urna. Donec nibh. Integer in purus tempus mi venenatis mollis. Cras nunc odio, porttitor at, accumsan ac, adipiscing vitae, ante.</p>
34                 <p>Nam dui enim, fringilla vitae, rhoncus non, pharetra in, nunc. Sed a lectus vel orci bibendum placerat. Aliquam erat volutpat. Integer odio. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis dictum egestas lorem. Donec ultricies volutpat tellus. Phasellus justo arcu, pharetra eget, cursus non, consectetuer ac, nunc. Fusce orci tortor, semper vel, lacinia vitae, accumsan id, quam. Mauris semper molestie lectus. Duis venenatis erat ultrices nisl.</p>
35                 <p>Morbi augue enim, ultricies nec, lobortis sed, iaculis eu, quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Curabitur sollicitudin, elit eu porttitor varius, tellus velit tristique sem, vitae blandit nisi eros id purus. Nunc non lorem. Nunc blandit purus nec nisi. Donec vulputate, urna vel interdum tristique, tellus mauris pretium lacus, quis sodales lectus nunc sit amet turpis. Suspendisse potenti. Fusce accumsan. Maecenas aliquam consectetuer augue. Fusce est neque, condimentum nec, condimentum vitae, consectetuer ac, tortor. Praesent ultricies urna in lectus. Nam erat nunc, venenatis nec, facilisis sed, feugiat ac, pede. Vivamus aliquam aliquet libero. Curabitur dolor nunc, scelerisque at, gravida dignissim, rutrum at, orci. Maecenas vitae libero id eros rutrum hendrerit. Duis lacinia mauris non erat. Nullam et dolor vel leo sollicitudin suscipit. Sed laoreet libero.</p>
36                 <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent turpis. Suspendisse molestie, neque non congue ullamcorper, neque sem consequat nisl, eget pulvinar odio erat et tellus. Nunc luctus convallis dolor. Nullam non mauris. Etiam nisi magna, adipiscing eu, nonummy ac, laoreet nec, est. Pellentesque tristique, est vel condimentum feugiat, nisi justo rhoncus pede, in pulvinar mauris lectus vitae dui. Pellentesque scelerisque. Vestibulum tellus dolor, porta quis, facilisis nec, convallis vitae, quam. Quisque nisi. Nunc vitae nulla vel turpis mollis molestie. Etiam vitae massa.<</p>
37             </div>
38         </div>
39         <p style="clear: left;">
40             You can add more copy to pane4 by clicking <a href="javascript:;" id="add-content">here</a> -
41             this illustrates how to update the scrollbar when content is dynamically added to a page (e.g.
42             as the result of an AJAX call). You can also reduce the amount of content in pane4 by clicking
43             <a href="javascript:;" id="remove-content">here</a>.
44         </p>
45     </body>
46 </html>
View Code

js滚动条代码

(function ($) {

    $.jScrollPane = {
        active: []
    };
    $.fn.jScrollPane = function (settings) {
        settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

        var rf = function () { return false; };

        return this.each(
        function () {
            var $this = $(this);
            var paneEle = this;
            var currentScrollPosition = 0;
            var paneWidth;
            var paneHeight;
            var trackHeight;
            var trackOffset = settings.topCapHeight;
            var $container;

            if ($(this).parent().is('.jScrollPaneContainer')) {
                $container = $(this).parent();
                currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
                var $c = $(this).parent();
                paneWidth = $c.innerWidth();
                paneHeight = $c.outerHeight();
                $('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScrollCap', $c).remove();
                $this.css({ 'top': 0 });
            } else {
                $this.data('originalStyleTag', $this.attr('style'));
                // Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
                $this.css('overflow', 'hidden');
                this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
                this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
                paneWidth = $this.innerWidth();
                paneHeight = $this.innerHeight();
                $container = $('<div></div>')
                    .attr({ 'className': 'jScrollPaneContainer' })
                    .css(
                        {
                            'height': paneHeight + 'px', //容器高度设置
                            'width': paneWidth + 'px'
                        }
                    );
                if (settings.enableKeyboardNavigation) {
                    $container.attr(
                        'tabindex',
                        settings.tabIndex
                    );
                }
                $this.wrap($container);
                $container = $this.parent();
                // deal with text size changes (if the jquery.em plugin is included)
                // and re-initialise the scrollPane so the track maintains the
                // correct size
                $(document).bind(
                    'emchange',
                    function (e, cur, prev) {
                        $this.jScrollPane(settings);
                    }
                );

            }
            trackHeight = paneHeight;

            if (settings.reinitialiseOnImageLoad) {
                // code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
                // except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
                // TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
                var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
                var loadedImages = [];

                if ($imagesToLoad.length) {
                    $imagesToLoad.each(function (i, val) {
                        $(this).bind('load readystatechange', function () {
                            if ($.inArray(i, loadedImages) == -1) { //don't double count images
                                loadedImages.push(val); //keep a record of images we've seen
                                $imagesToLoad = $.grep($imagesToLoad, function (n, i) {
                                    return n != val;
                                });
                                $.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
                                var s2 = $.extend(settings, { reinitialiseOnImageLoad: false });
                                $this.jScrollPane(s2); // re-initialise
                            }
                        }).each(function (i, val) {
                            if (this.complete || this.complete === undefined) {
                                //needed for potential cached images
                                this.src = this.src;
                            }
                        });
                    });
                };
            }

            var p = this.originalSidePaddingTotal;
            var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

            var cssToApply = {
                'height': 'auto',
                'width': realPaneWidth + 'px'
            }

            if (settings.scrollbarOnLeft) {
                cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
            } else {
                cssToApply.paddingRight = settings.scrollbarMargin + 'px';
            }

            $this.css(cssToApply);

            var contentHeight = $this.outerHeight();
            var percentInView = paneHeight / contentHeight;

            var isScrollable = percentInView < .99;
            $container[isScrollable ? 'addClass' : 'removeClass']('jScrollPaneScrollable');

            if (isScrollable) {
                $container.append(
                    $('<div></div>').addClass('jScrollCap jScrollCapTop').css({ height: settings.topCapHeight }),
                    $('<div></div>').attr({ 'className': 'jScrollPaneTrack' }).css({ 'width': settings.scrollbarWidth + 'px' }).append(
                        $('<div></div>').attr({ 'className': 'jScrollPaneDrag' }).css({ 'width': '6px' }).append(
                            $('<div></div>').attr({ 'className': 'jScrollPaneDragTop' }).css({ 'width': settings.scrollbarWidth + 'px' }),
                            $('<div></div>').attr({ 'className': 'jScrollPaneDragBottom' }).css({ 'width': settings.scrollbarWidth + 'px' })
                        )
                    ),
                    $('<div></div>').addClass('jScrollCap jScrollCapBottom').css({ height: settings.bottomCapHeight })
                );

                var $track = $('>.jScrollPaneTrack', $container);
                var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);


                var currentArrowDirection;
                var currentArrowTimerArr = []; // Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
                var currentArrowInc;
                var whileArrowButtonDown = function () {
                    if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
                        positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
                    }
                    currentArrowInc++;
                };

                if (settings.enableKeyboardNavigation) {
                    $container.bind(
                        'keydown.jscrollpane',
                        function (e) {
                            switch (e.keyCode) {
                                case 38: //up
                                    currentArrowDirection = -1;
                                    currentArrowInc = 0;
                                    whileArrowButtonDown();
                                    currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
                                    return false;
                                case 40: //down
                                    currentArrowDirection = 1;
                                    currentArrowInc = 0;
                                    whileArrowButtonDown();
                                    currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
                                    return false;
                                case 33: // page up
                                case 34: // page down
                                    // TODO
                                    return false;
                                default:
                            }
                        }
                    ).bind(
                        'keyup.jscrollpane',
                        function (e) {
                            if (e.keyCode == 38 || e.keyCode == 40) {
                                for (var i = 0; i < currentArrowTimerArr.length; i++) {
                                    clearInterval(currentArrowTimerArr[i]);
                                }
                                return false;
                            }
                        }
                    );
                }

                if (settings.showArrows) {

                    var currentArrowButton;
                    var currentArrowInterval;

                    var onArrowMouseUp = function (event) {
                        $('html').unbind('mouseup', onArrowMouseUp);
                        currentArrowButton.removeClass('jScrollActiveArrowButton');
                        clearInterval(currentArrowInterval);
                    };
                    var onArrowMouseDown = function () {
                        $('html').bind('mouseup', onArrowMouseUp);
                        currentArrowButton.addClass('jScrollActiveArrowButton');
                        currentArrowInc = 0;
                        whileArrowButtonDown();
                        currentArrowInterval = setInterval(whileArrowButtonDown, 100);
                    };
                    $container
                        .append(
                            $('<a></a>')
                                .attr(
                                    {
                                        'href': 'javascript:;',
                                        'className': 'jScrollArrowUp',
                                        'tabindex': -1
                                    }
                                )
                                .css(
                                    {
                                        'width': settings.scrollbarWidth + 'px',
                                        'top': settings.topCapHeight + 'px'
                                    }
                                )
                                .html('Scroll up')
                                .bind('mousedown', function () {
                                    currentArrowButton = $(this);
                                    currentArrowDirection = -1;
                                    onArrowMouseDown();
                                    this.blur();
                                    return false;
                                })
                                .bind('click', rf),
                            $('<a></a>')
                                .attr(
                                    {
                                        'href': 'javascript:;',
                                        'className': 'jScrollArrowDown',
                                        'tabindex': -1
                                    }
                                )
                                .css(
                                    {
                                        'width': settings.scrollbarWidth + 'px',
                                        'bottom': settings.bottomCapHeight + 'px'
                                    }
                                )
                                .html('Scroll down')
                                .bind('mousedown', function () {
                                    currentArrowButton = $(this);
                                    currentArrowDirection = 1;
                                    onArrowMouseDown();
                                    this.blur();
                                    return false;
                                })
                                .bind('click', rf)
                        );
                    var $upArrow = $('>.jScrollArrowUp', $container);
                    var $downArrow = $('>.jScrollArrowDown', $container);
                }

                if (settings.arrowSize) {
                    trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
                    trackOffset += settings.arrowSize;
                } else if ($upArrow) {
                    var topArrowHeight = $upArrow.height();
                    settings.arrowSize = topArrowHeight;
                    trackHeight = paneHeight - topArrowHeight - $downArrow.height();
                    trackOffset += topArrowHeight;
                }
                trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
                $track.css({ 'height': trackHeight + 'px', top: trackOffset + 'px' })

                var $pane = $(this).css({ 'position': 'absolute', 'overflow': 'visible' });

                var currentOffset;
                var maxY;
                var mouseWheelMultiplier;
                // store this in a seperate variable so we can keep track more accurately than just updating the css property..
                var dragPosition = 0;
                var dragMiddle = percentInView * paneHeight / 2;

                // pos function borrowed from tooltip plugin and adapted...
                var getPos = function (event, c) {
                    var p = c == 'X' ? 'Left' : 'Top';
                    return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
                };

                var ignoreNativeDrag = function () { return false; };

                var initDrag = function () {
                    ceaseAnimation();
                    currentOffset = $drag.offset(false);
                    currentOffset.top -= dragPosition;
                    maxY = trackHeight - $drag[0].offsetHeight;
                    mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
                };

                var onStartDrag = function (event) {
                    initDrag();
                    dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
                    $('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll).bind('mouseleave', onStopDrag)
                    if ($.browser.msie) {
                        $('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
                    }
                    return false;
                };
                var onStopDrag = function () {
                    $('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
                    dragMiddle = percentInView * paneHeight / 2;
                    if ($.browser.msie) {
                        $('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
                    }
                };
                var positionDrag = function (destY) {
                    $container.scrollTop(0);
                    destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
                    dragPosition = destY;
                    $drag.css({ 'top': destY + 'px' });
                    var p = destY / maxY;
                    $this.data('jScrollPanePosition', (paneHeight - contentHeight) * -p);
                    $pane.css({ 'top': ((paneHeight - contentHeight) * p) + 'px' });
                    $this.trigger('scroll');
                    if (settings.showArrows) {
                        $upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
                        $downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
                    }
                };
                var updateScroll = function (e) {
                    positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
                };

                var dragH = Math.max(Math.min(percentInView * (paneHeight - settings.arrowSize * 2), settings.dragMaxHeight), settings.dragMinHeight);

                $drag.css(
                    { 'height': dragH + 'px' }
                ).bind('mousedown', onStartDrag);

                var trackScrollInterval;
                var trackScrollInc;
                var trackScrollMousePos;
                var doTrackScroll = function () {
                    if (trackScrollInc > 8 || trackScrollInc % 4 == 0) {
                        positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
                    }
                    trackScrollInc++;
                };
                var onStopTrackClick = function () {
                    clearInterval(trackScrollInterval);
                    $('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
                };
                var onTrackMouseMove = function (event) {
                    trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
                };
                var onTrackClick = function (event) {
                    initDrag();
                    onTrackMouseMove(event);
                    trackScrollInc = 0;
                    $('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
                    trackScrollInterval = setInterval(doTrackScroll, 100);
                    doTrackScroll();
                    return false;
                };

                $track.bind('mousedown', onTrackClick);

                $container.bind(
                    'mousewheel',
                    function (event, delta) {
                        delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail / 3 : 0);
                        initDrag();
                        ceaseAnimation();
                        var d = dragPosition;
                        positionDrag(dragPosition - delta * mouseWheelMultiplier);
                        var dragOccured = d != dragPosition;
                        return !dragOccured;
                    }
                );

                var _animateToPosition;
                var _animateToInterval;
                function animateToPosition() {
                    var diff = (_animateToPosition - dragPosition) / settings.animateStep;
                    if (diff > 1 || diff < -1) {
                        positionDrag(dragPosition + diff);
                    } else {
                        positionDrag(_animateToPosition);
                        ceaseAnimation();
                    }
                }
                var ceaseAnimation = function () {
                    if (_animateToInterval) {
                        clearInterval(_animateToInterval);
                        delete _animateToPosition;
                    }
                };
                var scrollTo = function (pos, preventAni) {
                    if (typeof pos == "string") {
                        // Legal hash values aren't necessarily legal jQuery selectors so we need to catch any
                        // errors from the lookup...
                        try {
                            $e = $(pos, $this);
                        } catch (err) {
                            return;
                        }
                        if (!$e.length) return;
                        pos = $e.offset().top - $this.offset().top;
                    }
                    ceaseAnimation();
                    var maxScroll = contentHeight - paneHeight;
                    pos = pos > maxScroll ? maxScroll : pos;
                    $this.data('jScrollPaneMaxScroll', maxScroll);
                    var destDragPosition = pos / maxScroll * maxY;
                    if (preventAni || !settings.animateTo) {
                        positionDrag(destDragPosition);
                    } else {
                        $container.scrollTop(0);
                        _animateToPosition = destDragPosition;
                        _animateToInterval = setInterval(animateToPosition, settings.animateInterval);
                    }
                };
                $this[0].scrollTo = scrollTo;

                $this[0].scrollBy = function (delta) {
                    var currentPos = -parseInt($pane.css('top')) || 0;
                    scrollTo(currentPos + delta);
                };

                initDrag();

                scrollTo(-currentScrollPosition, true);

                // Deal with it when the user tabs to a link or form element within this scrollpane
                $('*', this).bind(
                    'focus',
                    function (event) {
                        var $e = $(this);

                        // loop through parents adding the offset top of any elements that are relatively positioned between
                        // the focused element and the jScrollPaneContainer so we can get the true distance from the top
                        // of the focused element to the top of the scrollpane...
                        var eleTop = 0;

                        var preventInfiniteLoop = 100;

                        while ($e[0] != $this[0]) {
                            eleTop += $e.position().top;
                            $e = $e.offsetParent();
                            if (!preventInfiniteLoop--) {
                                return;
                            }
                        }

                        var viewportTop = -parseInt($pane.css('top')) || 0;
                        var maxVisibleEleTop = viewportTop + paneHeight;
                        var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
                        if (!eleInView) {
                            var destPos = eleTop - settings.scrollbarMargin;
                            if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
                                destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
                            }
                            scrollTo(destPos);
                        }
                    }
                )


                if (settings.observeHash) {
                    if (location.hash && location.hash.length > 1) {
                        setTimeout(function () {
                            scrollTo(location.hash);
                        }, $.browser.safari ? 100 : 0);
                    }

                    // use event delegation to listen for all clicks on links and hijack them if they are links to
                    // anchors within our content...
                    $(document).bind('click', function (e) {
                        $target = $(e.target);
                        if ($target.is('a')) {
                            var h = $target.attr('href');
                            if (h && h.substr(0, 1) == '#' && h.length > 1) {
                                setTimeout(function () {
                                    scrollTo(h, !settings.animateToInternalLinks);
                                }, $.browser.safari ? 100 : 0);
                            }
                        }
                    });
                }

                // Deal with dragging and selecting text to make the scrollpane scroll...
                function onSelectScrollMouseDown(e) {
                    $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
                    $(document).bind('mouseup.jScrollPaneDragging', onSelectScrollMouseUp);

                }

                var textDragDistanceAway;
                var textSelectionInterval;

                function onTextSelectionInterval() {
                    direction = textDragDistanceAway < 0 ? -1 : 1;
                    $this[0].scrollBy(textDragDistanceAway / 2);
                }

                function clearTextSelectionInterval() {
                    if (textSelectionInterval) {
                        clearInterval(textSelectionInterval);
                        textSelectionInterval = undefined;
                    }
                }

                function onTextSelectionScrollMouseMove(e) {
                    var offset = $this.parent().offset().top;
                    var maxOffset = offset + paneHeight;
                    var mouseOffset = getPos(e, 'Y');
                    textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
                    if (textDragDistanceAway == 0) {
                        clearTextSelectionInterval();
                    } else {
                        if (!textSelectionInterval) {
                            textSelectionInterval = setInterval(onTextSelectionInterval, 100);
                        }
                    }
                }

                function onSelectScrollMouseUp(e) {
                    $(document)
                      .unbind('mousemove.jScrollPaneDragging')
                      .unbind('mouseup.jScrollPaneDragging');
                    clearTextSelectionInterval();
                }

                $container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);


                $.jScrollPane.active.push($this[0]);

            } else {
                $this.css(
                    {
                        'height': paneHeight + 'px',
                        'width': paneWidth - this.originalSidePaddingTotal + 'px',
                        'padding': this.originalPadding
                    }
                );
                $this[0].scrollTo = $this[0].scrollBy = function () { };
                // clean up listeners
                $this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
            }

        }
    )
    };

    $.fn.jScrollPaneRemove = function () {
        $(this).each(function () {
            $this = $(this);
            var $c = $this.parent();
            if ($c.is('.jScrollPaneContainer')) {
                $this.css(
                {
                    'top': '',
                    'height': '',
                    'width': '',
                    'padding': '',
                    'overflow': '',
                    'position': ''
                }
            );
                $this.attr('style', $this.data('originalStyleTag'));
                $c.after($this).remove();
            }
        });
    }

    $.fn.jScrollPane.defaults = {
        scrollbarWidth: 10,
        scrollbarMargin: 5,
        wheelSpeed: 18,
        showArrows: false,
        arrowSize: 0,
        animateTo: false,
        dragMinHeight: 1,
        dragMaxHeight: 99999,
        animateInterval: 100,
        animateStep: 3,
        maintainPosition: true,
        scrollbarOnLeft: false,
        reinitialiseOnImageLoad: false,
        tabIndex: 0,
        enableKeyboardNavigation: true,
        animateToInternalLinks: false,
        topCapHeight: 0,
        bottomCapHeight: 0,
        observeHash: true
    };

    // clean up the scrollTo expandos
    $(window)
    .bind('unload', function () {
        var els = $.jScrollPane.active;
        for (var i = 0; i < els.length; i++) {
            els[i].scrollTo = els[i].scrollBy = null;
        }
    }
);

})(jQuery);
View Code
(function($) {

$.event.special.mousewheel = {
    setup: function() {
        var handler = $.event.special.mousewheel.handler;
        
        // Fix pageX, pageY, clientX and clientY for mozilla
        if ( $.browser.mozilla )
            $(this).bind('mousemove.mousewheel', function(event) {
                $.data(this, 'mwcursorposdata', {
                    pageX: event.pageX,
                    pageY: event.pageY,
                    clientX: event.clientX,
                    clientY: event.clientY
                });
            });
    
        if ( this.addEventListener )
            this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
        else
            this.onmousewheel = handler;
    },
    
    teardown: function() {
        var handler = $.event.special.mousewheel.handler;
        
        $(this).unbind('mousemove.mousewheel');
        
        if ( this.removeEventListener )
            this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
        else
            this.onmousewheel = function(){};
        
        $.removeData(this, 'mwcursorposdata');
    },
    
    handler: function(event) {
        var args = Array.prototype.slice.call( arguments, 1 );
        
        event = $.event.fix(event || window.event);
        // Get correct pageX, pageY, clientX and clientY for mozilla
        $.extend( event, $.data(this, 'mwcursorposdata') || {} );
        var delta = 0, returnValue = true;
        
        if ( event.wheelDelta ) delta = event.wheelDelta/120;
        if ( event.detail     ) delta = -event.detail/3;
//        if ( $.browser.opera  ) delta = -event.wheelDelta;
        
        event.data  = event.data || {};
        event.type  = "mousewheel";
        
        // Add delta to the front of the arguments
        args.unshift(delta);
        // Add event to the front of the arguments
        args.unshift(event);

        return $.event.handle.apply(this, args);
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },
    
    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});

})(jQuery);
View Code

css代码:

.jScrollPaneContainer {
    position: relative;
    overflow: hidden;
    z-index: 1;
}

.jScrollPaneTrack {
    position: absolute;
    cursor: pointer;
    right: 0;
    top: 0;
    height: 100%;
    background: url("/images/jScrollPaneTrack.png") repeat-y scroll -2px 0 transparent;
}
.jScrollPaneDrag {
    position: absolute;
    background: url("/images/jScrollPaneDrag-mid.png") no-repeat scroll center center #fff;
    cursor: pointer;
    overflow: hidden;
    border-radius: 3px 3px 3px 3px;
    border:1px solid #ddd;
}
.jScrollPaneDragTop {
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
}
.jScrollPaneDragBottom {
    position: absolute;
    bottom: 0;
    left: 0;
    overflow: hidden;
}
a.jScrollArrowUp {
    display: block;
    position: absolute;
    z-index: 1;
    top: 0;
    right: 0;
    text-indent: -2000px;
    overflow: hidden;
    /*background-color: #666;*/
    height: 9px;
}
a.jScrollArrowUp:hover {
    /*background-color: #f60;*/
}

a.jScrollArrowDown {
    display: block;
    position: absolute;
    z-index: 1;
    bottom: 0;
    right: 0;
    text-indent: -2000px;
    overflow: hidden;
    /*background-color: #666;*/
    height: 9px;
}
a.jScrollArrowDown:hover {
    /*background-color: #f60;*/
}
a.jScrollActiveArrowButton, a.jScrollActiveArrowButton:hover {
    /*background-color: #f00;*/
}
View Code
/* Stylesheet for my demo pages for jScrollPane - these styles aren't necessary for using jScrollPane and aren't specific to any particular example */

body {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 80%;
}

a.jScrollArrowUp {
    background: url(../images/basic_arrow_up.gif) repeat-x 0 0;
}
a.jScrollArrowUp:hover {
    background-position: 0 -15px;
}
a.jScrollArrowDown {
    background: url(../images/basic_arrow_down.gif) repeat-x 0 0;
}
a.jScrollArrowDown:hover {
    background-position: 0 -15px;
}
a.jScrollActiveArrowButton, a.jScrollActiveArrowButton:hover {
    background-position: 0 -30px;
}


.orange-bar .jScrollPaneTrack {
    background: #f60;
}
.orange-bar .jScrollPaneDrag {
    background: #00f url(../images/drag_grab.gif) no-repeat 50% 50%;
}
.orange-bar .scroll-pane {
    background: #69f;
}
            
.holder {
    float: left;
    margin: 10px;
}

.scroll-pane {
    width: 200px;
    height: 200px;
    overflow: auto;
    background: #ccc;
    float: left;
}

.wide {
    width: 400px;
}

.super-wide {
    width: 700px;
}

.tall {
    height: 400px;
}

#pane1 {
}
#pane2 {
    height: 150px;
}
#pane3 {
    height: 190px;
}
#pane4 {
    height: 190px;
}
View Code

第一篇博客,代码算是贴全了!传说每一个第一次都值得纪念....

  

  

原文地址:https://www.cnblogs.com/yushang/p/2853936.html