Home Web Front-end JS Tutorial Follow screen scrolling code based on jquery_jquery

Follow screen scrolling code based on jquery_jquery

May 16, 2016 pm 05:51 PM
follow

So how is this achieved? This article will quote Wutu Bang’s follow-screen scrolling code to explain this effect in detail.
1. Original code
The following is Wutu Bang’s screen scrolling code. Its scope is the sidebars on both sides of Wutu Bang’s web page, and the hidden bar on the right after double-clicking the screen. .

Copy code The code is as follows:

var $catalogueOffsetTop = $('aside#catalogue').offset().top;
var $archiveOffestTop = $('aside#archive').offset().top;
var $archiveOffestLeft = $('aside#archive').offset().left;
$(window).bind('scroll resize',function(){
// #right-area的跟随屏幕滚动效果
if($('#right-area').height() <= $(window).height()){
$('#right-area').stop(true,true).animate({'top': $(document).scrollTop() 'px'},800);
}else if($('#right-area').height() > $(window).height() && $('#right-area').height() < $(document).height()){
// 这段范围内是最关键的,允许滑动
if(($(document).scrollTop() $(window).height()) <= $('#right-area').height()){
$('#right-area').stop(true,true).css('top','0');
}else if(($(document).scrollTop() $(window).height()) < $(document).height()){
$right_top = $(document).scrollTop() $(window).height() - $('#right-area').height();
$('#right-area').stop(true,true).animate({'top': $right_top 'px'},800);
}else{
$right_top = $(document).height() - $('#right-area').height();
$('#right-area').stop(true,true).css({'top': $right_top 'px'});
//alert($(document).scrollTop() $(window).height() - $(document).height());
}
}else if($('#right-area').height() >= $(document).height()){
$('#right-area').height($(document).height()).stop(true,true).css({'overflow':'hidden','overflow-y':'scroll'});
}
if($(document).scrollLeft() == 0){ // 只有在屏幕处于左侧的时候才进行下面的跟随滚动,同时需要注意下面的if($(window).width() > 1024),是为了防止在小屏幕下还发生这种变化
// aside#catalogue的上下滑动
if($('aside#catalogue').outerHeight() < $(window).height()){
if($(document).scrollTop() <= $catalogueOffsetTop){
$('aside#catalogue').css({'position':'static','top':$catalogueOffsetTop});
if($(window).width() > 1024)$('#main').css({'padding-left':'0'});
}else{
$('aside#catalogue').css({'position':'fixed','top':'0'});
if($(window).width() > 1024)$('#main').css({'padding-left':$('aside#catalogue').outerWidth() 5 'px'});
}
}else if($('aside#catalogue').height() >= $(window).height() && $('aside#catalogue').outerHeight() < ($('footer').offset().top - $catalogueOffsetTop)){
if(($(document).scrollTop() $(window).height()) <= ($('aside#catalogue').outerHeight() $catalogueOffsetTop)){
$('aside#catalogue').css({'position':'static','top':$catalogueOffsetTop});
if($(window).width() > 1024)$('#main').css({'padding-left':'0'});
}else if(($(document).scrollTop() $(window).height()) < $('footer').offset().top){
$catalogue_top = $(window).height() - $('aside#catalogue').outerHeight() - 20;
$('aside#catalogue').css({'position':'fixed','top': $catalogue_top 'px'});
if($(window).width() > 1024)$('#main').css({'padding-left':$('aside#catalogue').outerWidth() 5 'px'});
}else{
$catalogue_top = $(window).height() - $('aside#catalogue').outerHeight() - 20 - ($(document).height() - $('footer').offset().top);
$('aside#catalogue').css({'position':'fixed','top':$catalogue_top 'px'});
if($(window).width() > 1024)$('#main').css({'padding-left':$('aside#catalogue').outerWidth() 5 'px'});
}
}
// aside#archive的上下滑动
if($('aside#archive').outerHeight() < $(window).height()){
if($(document).scrollTop() <= $archiveOffestTop){
$('aside#archive').css({'position':'static','top':$archiveOffestTop,'left':$archiveOffestLeft 'px'});
}else{
$('aside#archive').css({'position':'fixed','top':'0','left':$archiveOffestLeft 'px'});
}
}else if($('aside#archive').height() >= $(window).height() && $('aside#archive').outerHeight() < ($('footer').offset().top - $archiveOffestTop)){
if(($(document).scrollTop() $(window).height()) <= ($('aside#archive').outerHeight() $archiveOffestTop)){
$('aside#archive').css({'position':'static','top':$archiveOffestTop,'left':$archiveOffestLeft 'px'});
}else if(($(document).scrollTop() $(window).height()) < $('footer').offset().top){
$catalogue_top = $(window).height() - $('aside#archive').outerHeight();
$('aside#archive').css({'position':'fixed','top': $catalogue_top 'px','left':$archiveOffestLeft 'px'});
}else{
$catalogue_top = $(window).height() - $('aside#archive').outerHeight() - ($(document).height() - $('footer').offset().top);
$('aside#archive').css({'position':'fixed','top':$catalogue_top 'px','left':$archiveOffestLeft 'px'});
}
}
}else{ // 如果屏幕不处于左侧,就让这两个跟随归位
$('aside#catalogue').css({'position':'static','top':$catalogueOffsetTop});
$('#main').css({'padding-left':'0'});
$('aside#archive').css({'position':'static','top':$archiveOffestTop,'left':$archiveOffestLeft 'px'});
}
}).scroll().resize();

There are a lot of related codes on the Internet, there are even 7 lines of code to solve this problem, and there are even universal plug-ins to achieve this Effect. However, they are all too general. Different websites have different particularities, and more considerations need to be made in some details.

2. Choose how to follow the screen scrolling
There are three options:

1. Use position:absolute; and then dynamically assign the top value;
2. Use position:fixed; and then dynamically assign the top value;
3. Dynamically assign padding-top or margin-top;

The first two use postion elements Arrange the position of the element. Like float, position drags the element out of the normal text flow. The padding or margin method is achieved by controlling the margin of the element. Which one is better?

Using position:absolute; will cause jitter when scrolling (not in Firefox). When using padding-top, elements with backgrounds will look ugly and jitter will occur. Using position:fixed is not supported. IE6, I have not tried using margin-top, it should cause jitter. This code selects position:fixed, which is the only solution that does not cause jitter, but this effect will not occur under IE6.

3. Situations to consider
The reason why Wutu Gang wants to explain the code of this site is because there is no detailed analysis of the code on the Internet, and many issues are not considered arrive.

1. Compare the height of the element to be followed with the height of the screen

All the codes on the Internet consider the situation that the height of the area is less than the height of the window, so the code is very simple. When the area height is equal to and greater than the window height, we have new considerations.

2. If the height of the area exceeds the window, when will it start to follow the scrolling?

It depends on what we want to show the user, if it is an advertisement, if it is a paragraph of text, if it is a list. My design is that when the screen scrolls down, but all the elements to be displayed have not been fully displayed, no effect will be performed. When the screen scrolls to the bottom critical point of the element, the effect is triggered. When scrolling down again, the element's The bottom edge is aligned with the bottom edge of the screen, so that the lower part of the element is always rendered within the screen. Of course, your design will naturally differ for different web pages. You may also design it so that there is no effect when scrolling down. When you scroll to an ad, the ad will be aligned with the top of the screen and scroll.

Figure 1 Follow the screen scrolling logic design

Let’s take a look at this design idea from Figure 1. The green part in the picture is the area to be scrolled, the gray part is the entire web page, and the light gray part is the screen (the area that can be seen). We simulate downward scrolling by moving the light gray screen downwards. Stage ① is the initial stage. At this time, the web page operates as it was initially without any action. At stage ②, the screen scrolls down to a critical point, that is, it follows the lowest end of the scrolling area. Stage ③ is after scrolling past the critical point, the element begins to scroll with the screen. We can see that the bottom of the element is aligned with the bottom of the screen, and the top of the element is no longer visible. In the fourth stage, the screen scrolls to the bottom. It can be imagined that there is some copyright information at the bottom of the web page. The elements cannot follow the scroll to the bottom to cover this information, so the red line will no longer follow the scroll.

This is a schematic diagram of the screen scrolling down. When the screen scrolls up, this is the reverse of this sequence. But there is another consideration. When the screen is scrolling up, it achieves an effect similar to the initial state when scrolling down. That is, the critical point is the top of the green area in ④ at this time. When scrolling up, the top of the screen is aligned with the top of the element. Due to technical difficulties, Wutu Gang did not achieve this effect.

3. Calculation of numbers and quantities

When scrolling, we must grasp which quantities change and which do not change. Find changes in the changes and find changes in the changes. In short, you must keep your mind clear and understand how to calculate various height relationships.

In Figure 1, I used a blue vertical line to assist in height calculation, used a red line to indicate the position of the screen and elements, and divided the blue vertical line into a, b, c, d, Six paragraphs e and f. So what are the changing quantitative relationships between them? (We define the elements in the green area as #myDiv, and the bottom including the copyright information as #footer)

a b c d e f=$(document).height();//Document height, fixed value
Copy code The code is as follows:

a= $('#myDiv').offset().top;//The initial value from the top of #myDiv to the top of the document, with scrolling, $('#myDiv').offset(). top will change

b=$('#myDiv').height();//The height of the element, fixed value

a b c=$(window).scrollTop()=$ (docment).scrollTop();//The position of the scroll bar, that is, the distance from the top of the document to the top of the current screen, is constantly changing

d=$(window).height();//Height of the screen , fixed value

f=$('#footer').height();//Height of #footer, fixed value

a b c d e=$('#footer').offset( ).top=$(document).height()-$('#footer').height();//The distance from the top of #footer to the top of the document, fixed value, but it should be noted that $('#footer ').offset().top $('#footer').height() is not necessarily equal to $(document).height(). You have to check whether there is no blank space under #footer.

During the entire change process, the only changed values ​​are $(window).scrollTop()=$(docment).scrollTop() and $('#myDiv').offset().top , so we need to grasp the quantitative relationship between addition and subtraction between these values, and make logical judgments and assignments.

4. When is the value obtained?

You can see that I obtained it before the scroll event.
Copy code The code is as follows:

var $catalogueOffsetTop = $('aside#catalogue').offset().top;
var $archiveOffestTop = $('aside #archive').offset().top;
var $archiveOffestLeft = $('aside#archive').offset().left;

It is because they occur in the scroll event will change over time, so it must be stored in a variable in advance.

4. Special considerations for special situations

Before writing so much code, I once thought about writing a code that can be used universally. However, things are not that simple. In Utu Gang, the three areas to be rolled all have special characteristics, so their event logic must be carefully considered and carefully assigned.

1. Whether the elements are free and arbitrary

Because the area that appears when Wu Tu Bang double-clicks the screen and slides to the right is free, and there is no blocking information at the top and bottom, so our processing is more convenient. , there is no need to obtain the initial value of the top distance and consider leaving a space when scrolling to the bottom. But you still have to consider point 2 below, the comparison of screen and element height.

As for the scrolling of the sidebar, we have to consider that there is still a distance from the top of the sidebar to the top of the document, and there is also copyright information at the bottom. The rolled position must be accurately calculated based on the value obtained above, and then combined with the value obtained in css.

2. Determine the relationship between the height of the element and the height of the screen

When the height of the element is small, our processing is relatively simple. We only need to align the top of the element with the top of the screen, and above Combining the first point, a different situation will also arise: if there is still some distance between the top of the element and the top of the document, we cannot start to align it with the top of the screen as soon as the screen scrolls, but must scroll to the critical point of its top. time to start.

When the height of the element is greater than the height of the screen, we need to make a more complex judgment, and the first point is to judge when to start following the scroll: only when the bottom of the screen is aligned with the bottom of the element, The element starts scrolling with the screen.

But there is another situation, that is, the height of the element exceeds the height we want. We can use overflow to process the element. At this time, we compare the height of the element with some fixed values ​​​​in the page. handle this aspect. Wutu Bang handles overflow by comparing the relationship between the height and the bottom of the right element:
Copy code The code is as follows:

......
}else if($('#right-area').height() >= ($('footer').offset().top $('footer').height())){
$('#right-area').height($('footer').offset().top $('footer').height() ).stop(true,true).css({'overflow':'hidden','overflow-y':'scroll'});
}

3. Within your own web page Changes in special circumstances

Wutubang has a series of problems because it can still scroll left and right. When position:fixed, the distance between elements in the left and right directions does not have a fixed value, so when scrolling left or right, the elements will Cover the scrolled screen, so I judged $(document).scrollLeft() and performed some processing.

In addition, Wutu Bang is also an adaptive web design website, which displays different effects on screens of different widths. The characteristic of js is that it still works when the screen changes. Therefore, I also added Determination of screen width.

Summary
Regarding the issue of following the scrolling of the screen, the original idea is very simple, that is, dynamically changing the position or distance through the three solutions listed in this article. However, it is necessary to grasp the specific details. Well, you must have a grasp of each value in dynamic changes. At the same time, combined with your own web page, you have a good design and plan for the dynamic effects under different situations, which is also a key link to achieve scrolling with the screen.
Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins 10 jQuery Fun and Games Plugins Mar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header Background jQuery Parallax Tutorial - Animated Header Background Mar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Getting Started With Matter.js: Introduction Getting Started With Matter.js: Introduction Mar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAX Auto Refresh Div Content Using jQuery and AJAX Mar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

See all articles