JavaScript custom scroll bar implementation code_javascript skills
In work, we often encounter content that exceeds a fixed range. Generally, scroll bars are used to scroll and display the exceeded content.
But using the default scroll bar of the browser is often looked down upon by product managers, but the style of the scroll bar cannot be changed using css. Fortunately, there is a universal js ^_^~~
There are various plug-ins on the Internet, but the most convenient one is to write it yourself. You can also learn while playing, and make enough food and clothing by yourself (*^__^*)
These three questions deeply bother me:
- 1. Scroll bar height
- 2. How far should the scroll bar move each time the up and down buttons are clicked
- 3. How much does the page need to move every time the scroll bar is dragged 1px?
The entire frame probably looks like this:
Let’s look at the first question first.
Since we already know the height of the content area, the visual height of the content and the height of the scrollable area of the scroll bar, since the content area and the distance of each movement of the scroll bar are proportional, the first question is very good Solution:
Scroll bar movable range / scroll bar height = content height / content visible height
How far should the scroll bar move each time the button is clicked?
Here I set a value for the parameter distance to determine how far the content area should scroll each time the button is clicked. Changing this value can change the scrolling speed of the content area. If you have better processing methods and suggestions, please tell me~
Currently, the distance of each scroll of the content area is known. What remains is to calculate how far the scroll bar should move?
Scroll bar movable range / scroll bar movement distance each time = content area height / content area movement distance each time
The effect is as follows:
There is another problem here, that is, you have to distinguish between a single click and a long press.
So you have to judge the time from pressing the button to releasing it. Currently it is set to <100ms for a single click, otherwise it is a long press:
When dragging the scroll bar, how much does the content area need to move for every 1px of scroll bar movement?
First know what percentage of the movable range of the scroll bar each 1PX distance accounts for, and then divide the content area height by the obtained percentage to get the relative scroll distance of the content area for each 1px movement of the scroll bar.
Content area scrolling distance = content area height / (scroll bar scrolling area / 1)
The complete code of the demo is as follows:
Note: Because it is written in seajs, please pay a little attention to the loading of the file
css:
.wapper{scrollbar-3dlight-color:#000; position:relative; height:302px;width:300px;overflow:hidden;margin:0 auto;line-height:40px;text-align:center;} .area{background-color:#E2E2EF;width:100%; position:absolute;top:0px;left:0px;} .bar{position:absolute;top:0px;right:0px; height:100%;width:1rem;background-color:#ccc;} .scroll,.middle,.forward,.backward{display:block;cursor:pointer;position:absolute;right:0px;width:100%;} .forward,.backward{height:16px;background-color:#6868B1;} .middle{background-color:rgba(255, 255, 255, 0.22);top:16px;cursor:auto;} .scroll{position:absolute;top:0px;background-color:#C2C2E9;} .forward{top:0px;} .backward{bottom:0px;}
html:
<div class="wapper"> <div class="area"> <p>1、this is content</p> <p>2、this is content</p> <p>3、this is content</p> <p>4、this is content</p> <p>5、this is content</p> <p>6、this is content</p> <p>7、this is content</p> <p>8、this is content</p> <p>9、this is content</p> <p>10、this is content</p> <p>11、this is content</p> </div> <div class="bar"> <span class="forward"></span> <span class="middle"><em class="scroll"></em></span> <span class="backward"></span> </div> </div> <script type="text/javascript" src="../../lib/seajs/sea.js"></script> <script type="text/javascript" src="../../lib/base/1.0.x/base.js"></script> <script type="text/javascript"> seajs.use(['lib/jquery/1.11.x/index.js', '_example/simulationScroll/simulationScroll.js'], function($, scroll) { scroll.init({ wapper: $('.wapper'), distance: 10, }); });
js:
define(function(require, exports, module) { 'use strict'; var $ = require('lib/jquery/1.11.x/index.js'); var parameter = null; //检测设备类型 var startWhen, endWhen, moveWhen; var u = navigator.userAgent; if ( u.match(/\b(Windows\sNT|Macintosh)\b/) ) { // 鼠标 startWhen = 'mousedown'; endWhen = 'mouseup'; moveWhen = 'mousemove'; } else { // 触摸屏 startWhen = 'touchstart'; endWhen = 'touchend'; moveWhen = 'touchmove'; } var simulation = { _mousedownTimer: 0, _setintervalId: 0, _longClick: false, //是否长点击 _turnOf: null, //滚动方向 init: function(options) { var t = this; t._scroll = $('.scroll'); //滚动条 t._wapper = options.wapper.find('.area'); //内容区域 t._distance = options.distance; //点击上下按钮页面每次滚动的距离 var forward = $('.forward'), middle = $('.middle'), backward = $('.backward'); parameter = { view: t._wapper.parent().innerHeight(), //视图高度 page: t._wapper.height(), //内容高度 barArea: 0, //滚动条可移动范围 scrollHeight: 0, //滚动条的高度 scrollDistance: 0 //滚动条每次滚动的距离 }; //初始化滚动条 if (parameter.page > parameter.view) { //滚动条可移动范围 middle.height( parameter.view - forward.height() * 2); parameter.barArea = middle.height(); //滚动条高度 = 滚动条可滚动范围 / (页面高度 / 可视高度)的百分比 parameter.scrollHeight = parameter.barArea / (parameter.page / parameter.view) ; t._scroll.height(parameter.scrollHeight); //滚动条每次滚动的距离 = 滚动条可移动范围 * 页面每次滚动的百分比 parameter.scrollDistance = parameter.barArea / (parameter.page / t._distance) ; //拖动滚动条 t.liveEvent(); //点击向前按钮,如果按下鼠标到松开鼠标的时长<100ms,则为单次点击 forward.bind(startWhen, function(e){ t._turnOf = 'forward'; t.longPress(e, t.direction ); }).bind(endWhen, function(e) { t.mouseupFun(e, t.direction); t._turnOf = null; }); //点击向后按钮 backward.bind(startWhen, function(e){ t.longPress(e, t.direction ); }).bind(endWhen, function(e){ t.mouseupFun(e, t.direction ); }); //注册鼠标滚动事件 // FF if(document.addEventListener){ document.addEventListener('DOMMouseScroll',t.mouseRuning,false); } //其它浏览器 document.onmousewheel = t.mouseRuning; } }, //鼠标滚动 mouseRuning: function(e) { var t = simulation; e = e || window.event; //ie、FF if (e.detail) { if (e.detail < 0) { t._turnOf = 'forward'; t.direction (); } else{ t._turnOf = null; t.direction (); } // chrome } else if(e.wheelDelta) { if (e.wheelDelta > 0) { t._turnOf = 'forward'; t.direction (); } else{ t._turnOf = null; t.direction (); } } }, //判断是否长点击 longPress: function(e, moveFun ) { var t = this; if ( u.match(/\b(Windows\sNT|Macintosh)\b/) ) { e = e || window.event; // 限制为鼠标左键点击才触发 if (/^mouse/.test(e.type) && e.which !== 1) { return; } } t._setintervalId = setInterval(function(){ t._mousedownTimer += 10; if( t._mousedownTimer >= 100 ){ moveFun(); } },20); }, mouseupFun: function(e, moveFun) { var t = this; if ( u.match(/\b(Windows\sNT|Macintosh)\b/) ) { e = e || window.event; // 限制为鼠标左键点击才触发 if (/^mouse/.test(e.type) && e.which !== 1) { return; } } clearTimeout(t._setintervalId); if( t._mousedownTimer < 100 ) { moveFun(); } t._mousedownTimer = 0; }, direction:function() { var t = simulation, barTop = t._scroll.position().top, pageTop = t._wapper.position().top, moveDistance = {}; if ( t._turnOf === 'forward') { //页面到顶,不执行任何操作 if (barTop == 0) { return; } moveDistance = { page: pageTop + t._distance, bar: barTop - parameter.scrollDistance } //如果滚动条距离顶部的距离少 < 每次滚动的距离,或者已经滚动到顶部,则不再滚动 if(barTop < parameter.scrollDistance || barTop <= 0){ moveDistance = { page: 0, bar: 0 } } } else { //页面到底,不执行任何操作 if (barTop == parameter.barArea - parameter.scrollHeight){ return; } moveDistance = { page: pageTop - t._distance, bar: barTop + parameter.scrollDistance }; // 如果滚动条距离底部的距离值 < 每次滚动的距离 或者已经到底部,则一次滚到底 if ( moveDistance.bar + parameter.scrollHeight >= parameter.barArea) { moveDistance = { page: parameter.view - parameter.page, bar: parameter.barArea - parameter.scrollHeight }; } } t._scroll.css({top: moveDistance.bar}); t._wapper.css({top: moveDistance.page}); }, //拖动滚动条 liveEvent: function() { var t = this, draging = false, currentY = 0, lastY = 0, pageY = 0; //检测设备类型 var _ua = function(e) { var Pos = null; if ( u.match(/\b(Windows\sNT|Macintosh)\b/) ) { e = e || window.event; // 限制为鼠标左键点击才触发 if (/^mouse/.test(e.type) && e.which !== 1) { return; } Pos = { left : e.pageX, top: e.pageY } } else { Pos = { left : e.originalEvent.targetTouches[0].pageX, top: e.originalEvent.targetTouches[0].pageY } } return Pos; }; var _start = function(e) { //监控鼠标 e.preventDefault(); if (t._scroll.get(0).setCapture) { t._scroll.get(0).setCapture(); } draging = true; //记录当前滚动条的坐标 lastY = t._scroll.position().top; //记录按下鼠标的坐标 pageY = _ua(e).top; }; var _drag = function(e) { if( draging ) { var pageTop = t._wapper.position().top; var barTop = t._scroll.position().top; //滚动条每移动1px,页面相对滚动Npx 再 * 当前滚动条的到顶部的距离 var pageMoveDistance = -(parameter.page / (parameter.barArea / 1)) * barTop; if (lastY + ( _ua(e).top - pageY ) < 0) { currentY = 0; pageMoveDistance = 0; } else if( lastY + ( _ua(e).top - pageY) + parameter.scrollHeight >= parameter.barArea) { currentY = parameter.barArea - parameter.scrollHeight; pageMoveDistance = parameter.view - parameter.page; } else { currentY = lastY + ( _ua(e).top - pageY); } t._scroll.css({ top:currentY}); t._wapper.css({top: pageMoveDistance}); } }; var _end = function(e) { if (draging) { draging = false; //在IE下释放对鼠标的控制 if (t._scroll.get(0).setCapture) { t._scroll.get(0).releaseCapture(); } document.onmousemove = null; document.onmouseup = null; } }; t._scroll.bind( startWhen, _start ); t._wapper.bind( startWhen, _start ); $(document).bind( moveWhen, _drag ); $(document).bind( endWhen, _end ); $(document).bind('blur', _end); } } return simulation; });
The above is the JavaScript simulation scroll bar implementation code. I hope it will be helpful to everyone's learning.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Recently, some friends have consulted the editor about how to set the scroll bar of the Mac system to always display. The following will bring you the method of setting the scroll bar of the Mac system to always display. Friends who need it can learn more. Step 1: In the system start menu, select the [System Preferences] option. Step 3: On the System Preferences page, select the [General] option. Step 3: On the general page, select [Always] to display scroll bars.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
