search
HomeWeb Front-endJS TutorialJS realizes the layer effect code that scrolls with the scroll bar on the web page_javascript skills

The example in this article describes the JS implementation of the layer effect code that scrolls with the scroll bar on the web page. Share it with everyone for your reference, the details are as follows:

The scrolling layer code on this webpage follows the scroll bar. Drag the scroll bar to see the effect. The code for the couplet advertisement is also based on this. The floating layer on the right can also be closed with a little processing. Implement the code for a floating ad, run it and see the effect first.

The screenshot of the running effect is as follows:

The online demo address is as follows:

http://demo.jb51.net/js/2015/js-web-fixed-scroll-adv-codes/

The specific code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>随滚动条滚动的层</title>
<style>
body{ margin:0; padding:0; font-size:12px; font-family:"宋体",Arial, Helvetica, sans-serif;}
div,p,ul,ol,li,dl,dt,dd,h1,h2,h3,h4,h5,h6,form,input,form{ margin:0; padding:0;}
h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}
img{ border:0;}
ol,ul{list-style:none;}
a{ text-decoration:none; color:#fff;}
a:hover{ text-decoration:none;}
#scroll_div{ width:100px; height:400px; background:#990; }
#btn_close,#btn_gotop{ cursor:pointer;}
</style>
</head>
<body>
<div style=" width:1002px;height:42px;margin:0 auto; background-color:#060;">头</div>
<div style="width:1002px; margin:0 auto; background-color:#f60;">
我们提供各类编程源码、<br>素材、书籍教程、设计模板、<br>网页特效代码以及常用软件下载等,<br>做有质量的<br>学习型源码下载站。
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
</div>
<div style=" width:1002px;height:95px;margin:0 auto; background-color:#060;">底</div>
<div id="scroll_div">
<span id="btn_close">关闭</span><br />
<span id="btn_gotop">返回顶部</span>
</div>
<script type="text/javascript">
var Bianyuan = {
 //添加事件2(DOM-保证this指向对象是obj)
 addEvent : function(obj, type, fn){
  if (obj.attachEvent){
   obj['e'+type+fn] = fn;
   obj[type+fn] = function(){obj['e'+type+fn](window.event);}
   obj.attachEvent('on'+type, obj[type+fn]);
  }else{
   obj.addEventListener(type, fn, false);
  }
 },
 //获取id元素
 $ : function(id){
  return document.getElementById(id);
 },
 //取得浏览器可视区size
 getBrowserSize : function(){
  var pageWidth = window.innerWidth,
   pageHeight = window.innerHeight;
  if (typeof pageWidth != "number"){
   if (document.compatMode == "CSS1Compat"){
    pageWidth = document.documentElement.clientWidth;
    pageHeight = document.documentElement.clientHeight;
   } else{
    pageWidth = document.body.clientWidth;
    pageWidth = document.body.clientHeight;
   }
  }
  //ie减去17滚动条宽度
  if(!window.ActiveXObject){
   pageWidth -= 17;
  }
  return {
   width : pageWidth,
   height : pageHeight
  }
 },
 //获取滚动条高度
 getPageScroll : function(){ 
  var yScroll; 
  if (self.pageYOffset) { 
   yScroll = self.pageYOffset; 
  } else if (document.documentElement && document.documentElement.scrollTop){ 
   yScroll = document.documentElement.scrollTop; 
  } else if (document.body) { 
   yScroll = document.body.scrollTop; 
  } 
  return yScroll; 
 }
}
function scrollBar(scrollId, dir, headHeight, footHeight, areaWidth, o){
 //滚动框宽高
 var scrollBar = Bianyuan.$(scrollId),
  barWidth = scrollBar.offsetWidth,
  barHeight = scrollBar.offsetHeight;
 //可视区宽高
 var pageWidth = Bianyuan.getBrowserSize().width,
  pageHeight = Bianyuan.getBrowserSize().height;
 //内容宽高
 var widthMore = document.documentElement.scrollWidth,
  heightMore = document.body.scrollHeight||(document.documentElement.scrollHeight);  
 //最大宽高
 var maxWidth = Math.max(pageWidth, widthMore),
  maxHeight = Math.max(pageHeight, heightMore);
 scrollBar.style.position = 'absolute';
 //设置top--假设滚动框高度小于整个页面高度,如果大于直接将其隐藏
 if (maxHeight < (barHeight + footHeight + footHeight + 4)){
  scrollBar.style.display = 'none';
 }else{
  //不挡顶部---如果想改距顶高度,改下边的第一个2值
  scrollBar.style.top = Bianyuan.getPageScroll() + headHeight + 2 + 'px';
  //不挡底部
  if ((heightMore - Bianyuan.getPageScroll() - barHeight) <= footHeight){
   scrollBar.style.top = heightMore - footHeight - barHeight - 2 + 'px';
  }
 }
 //无视主体内容-左右
 if (dir == 'left' && areaWidth == 1){
  scrollBar.style.left = 2 + 'px';
 }else if (dir == 'right' && areaWidth == 1){
  scrollBar.style.left = maxWidth - barWidth - 2 + 'px';
 //根据主体内容宽-左右
 }else if (dir == 'left' && areaWidth != 1){
  if (pageWidth >= (barWidth*2 + areaWidth + 4)){
   scrollBar.style.left = (pageWidth - areaWidth)/2 - barWidth - 2 + 'px';
  }else{
   scrollBar.style.left = 2 + 'px';
  }
 }else if (dir == 'right' && areaWidth != 1){
  if (pageWidth >= (barWidth*2 + areaWidth + 4)){
   scrollBar.style.left = (pageWidth - areaWidth)/2 + areaWidth + 2 + 'px';
  }else{
   scrollBar.style.left = maxWidth - barWidth - 2 + 'px';
  }
 }
 //关闭和返回顶部
 if (o){
  if (o.btnClose){
   var closeBtn = Bianyuan.$(o.btnClose);
   Bianyuan.addEvent(closeBtn, 'click', function(){
    scrollBar.style.display = 'none';
   })
  }
  if (o.goTop){
   var gotopBtn = Bianyuan.$(o.goTop);
   Bianyuan.addEvent(gotopBtn, 'click', function(){
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
   })
  }
 }
 //改变窗口大小或滚动条滚动
 resizeWindow(scrollId, dir, headHeight, footHeight, areaWidth, o);
}
function resizeWindow(scrollId, dir, headHeight, footHeight, areaWidth, o){
 window.onresize = function(){scrollBar(scrollId, dir, headHeight, footHeight, areaWidth, o);}
 window.onscroll = function(){scrollBar(scrollId, dir, headHeight, footHeight, areaWidth, o);}
}
</script>
<script type="text/javascript">
scrollBar("scroll_div", "right", 42, 95, 1002, {btnClose:"btn_close",goTop:"btn_gotop"});
</script>
</body>
</html>

I hope this article will be helpful to everyone in JavaScript programming.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool