1. Basic preparation:
scrollTop() method returns or sets the vertical position of the scroll bar of the matching element.
scroll top offset refers to the offset of the scroll bar relative to its top.
If this method sets no parameters, returns the offset in pixels from the top of the scroll bar.
Syntax
$(selector).scrollTop(offset)
2.
toggleClass() One or more to set or remove the selected element Switch between multiple classes.
For example, to switch the "main" class that sets and removes all
elements:
$("button").click(function(){
$("p").toggleClass("main");
});
3.
The setInterval() method can call a function or calculate an expression according to the specified period (in milliseconds).
The setInterval() method will keep calling the function until clearInterval() is called or the window is closed. The ID value returned by setInterval() can be used as an argument to the clearInterval() method.
4.
scrollTo() method can scroll the content to the specified coordinates.
scrollTo(xpos,ypos)
Parameter Description
xpos Required. The x-coordinate of the document to be displayed in the upper left corner of the window's document display area.
ypos required. The y-coordinate of the document to be displayed in the upper left corner of the window's document display area.
The code to achieve one-click upward is as follows:
var topbtn = $("#totop"); The button element that wants to go up with one click
var lastScroll = 0;
topbtn.css("display", "none");
window.onscroll = function(){ onscroll seems to be an attribute of HTML5
var top = $(window).scrollTop(); initially both are 0
if(top > 0){
topbtn.css("display" , "");
}
if(top == 0){If it is the starting state, the up icon will not be displayed
topbtn.css("display", "none");
}
};
topbtn.click(function(){ Click event
var scrollTop = 0;
var curPos = $(window).scrollTop(); Now the position of the scroll bar
topbtn.addClass("movingtotop"); Display another picture during movement
var step = Math.abs(scrollTop - curPos) / 200;
var tid = setInterval(function() {Continuously calling, Frame animation into a picture
topbtn.toggleClass("movingtotop"); An exquisite piece of code that uses the setting and deletion of element attributes alternately to create a dynamic flickering effect
if (curPos > scrollTop 14) {
curPos -= step;
step = step * 1.05; the speed gradually increases
window.scrollTo(0, curPos);
} else if (curPos <= scrollTop 14){jump directly to the beginning Position
window.scrollTo(0, scrollTop);
topbtn.removeClass("movingtotop");
clearInterval(tid); Close loop
}
}, 0.01);
});
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