我是hgg的初学者,想知道如何移动到html中的id,这是一个锚标记的目标,例如:
当我运行此代码时,它会快速转到目标ID,尽管我想要使用动画。我怎么能这样做?
答案 0 :(得分:0)
您可以使用jQuery
实现此目的。
这是执行平滑页面滚动到同一页面上的锚点的代码。它内置了一些逻辑来识别那些跳转链接,而不是针对其他链接。
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
答案 1 :(得分:0)
假设你的HTML是:
<a href = "#start-heading">Jump to start of content</a>
<div id = "table-of-contents">...</div>
<h1 id = "start-heading">Chapter 1</h1>
然后添加此javascript:
document.querySelector("#start-heading").onclick = e=>{
this.scrollIntoView({
behavior: 'smooth'
});
e.preventDefault();
return false;
};
document.querySelector("#start-heading").onclick = e=>{
document.querySelector(this.href).scrollIntoView({
behavior: 'smooth'
});
e.preventDefault();
return false;
};
<a href = "#start-heading">Jump to start of content</a>
<div id = "table-of-contents">
Bacon ipsum dolor amet flank shank meatloaf tri-tip picanha beef ribs sirloin strip steak fatback. Tenderloin boudin ground round biltong pig pancetta bacon tail porchetta strip steak leberkas fatback chicken venison tongue. Boudin short loin andouille drumstick prosciutto brisket, ham hock pork belly kevin jowl. Picanha turkey tenderloin shank, sirloin alcatra frankfurter tri-tip biltong drumstick filet mignon bresaola tongue ham hock. Boudin tri-tip ribeye salami. Kielbasa shankle cow ham hock landjaeger biltong shoulder turkey chuck pig chicken filet mignon. Ham drumstick pancetta, jerky spare ribs prosciutto frankfurter.
Boudin tail t-bone burgdoggen shank short ribs meatball. Salami andouille sausage porchetta. Sausage boudin jowl meatloaf, fatback drumstick kevin prosciutto turkey kielbasa sirloin biltong pig swine andouille. Kevin capicola picanha, tri-tip filet mignon ham pig jowl hamburger biltong brisket doner ground round.
Meatball boudin landjaeger alcatra ground round pancetta flank shank chuck bacon jerky jowl cupim. Ribeye pastrami tongue ham ground round shankle strip steak tenderloin, boudin ball tip hamburger. Brisket bacon hamburger, rump turducken jowl pig tongue venison tail kielbasa cow filet mignon ham. Tongue chicken ribeye porchetta t-bone. Corned beef flank turkey porchetta landjaeger. Pork loin tri-tip andouille, spare ribs jowl picanha pig ham pancetta cupim chuck filet mignon biltong sausage. Ground round pork belly biltong filet mignon t-bone, andouille bacon leberkas shoulder venison sausage tri-tip shank.
Doner ball tip frankfurter, pancetta chuck kielbasa bresaola meatloaf cupim. Cupim rump pork ham frankfurter burgdoggen kevin beef ribs ribeye porchetta shoulder swine beef filet mignon capicola. Tongue sausage strip steak short loin kevin doner beef ribs kielbasa chicken shank capicola bacon pastrami pork loin andouille. Burgdoggen alcatra frankfurter, spare ribs cupim biltong shoulder pig flank brisket.
</div>
<h1 id = "start-heading">Chapter 1</h1>
<p>
Bacon ipsum dolor amet rump ground round leberkas bresaola shoulder doner capicola shankle tri-tip beef ribs pork belly. Pork chop flank alcatra shoulder kielbasa cow ball tip venison turkey jerky hamburger. Kielbasa fatback sausage, drumstick tri-tip flank frankfurter pork chop pastrami. Jowl filet mignon flank ball tip short ribs turducken beef tail ribeye bacon t-bone sirloin tri-tip. Flank pork loin pork chop, fatback pancetta capicola alcatra doner t-bone meatball.
Kielbasa t-bone burgdoggen andouille pig venison turducken ground round short loin tenderloin strip steak pork chop corned beef porchetta. Rump short ribs meatloaf bacon shankle biltong tail hamburger salami flank chuck jowl pancetta pork loin filet mignon. Pig beef ribs venison alcatra rump cow cupim swine, salami drumstick boudin. Flank tri-tip picanha turkey pig corned beef. Turducken prosciutto andouille kevin cow chuck filet mignon landjaeger. Chuck turducken chicken brisket spare ribs. Porchetta cupim chuck, fatback biltong tail rump ground round sausage picanha.
Spare ribs shank drumstick meatball pork chop prosciutto pork belly sausage jerky andouille. Chicken hamburger pork belly ground round kevin leberkas pork loin rump ham picanha ribeye jerky alcatra andouille swine. Tenderloin ham pancetta beef ribs turducken ball tip. Kielbasa spare ribs capicola doner sirloin corned beef bresaola beef ribs pork chop. Pork belly prosciutto short ribs, kielbasa kevin alcatra short loin tongue sirloin meatloaf. Pork loin meatloaf t-bone sausage jerky chicken, ground round pig.
Meatloaf shankle ribeye jowl, chicken cow picanha turkey pork belly rump leberkas alcatra kielbasa tri-tip fatback. Bacon filet mignon cupim prosciutto pork belly. Corned beef hamburger ham hock, short ribs ham turkey cow fatback venison pastrami filet mignon jerky shankle chicken beef ribs. Prosciutto turducken turkey meatball, short loin kielbasa beef ribs tenderloin biltong venison ground round pork loin. Short loin filet mignon biltong jowl pig rump pork jerky drumstick strip steak swine ham hock beef bresaola ball tip. Pancetta tenderloin swine, meatloaf ham drumstick shank kevin salami.
Pork venison beef ribs rump hamburger. T-bone jerky prosciutto picanha kevin. Frankfurter ribeye shank tri-tip porchetta biltong tail filet mignon beef landjaeger sirloin leberkas jowl. Hamburger ham hock beef ribs shoulder biltong tenderloin sirloin burgdoggen. Cow cupim venison, biltong corned beef shankle meatloaf kevin ribeye capicola short loin ball tip ham hock. Strip steak spare ribs doner shoulder sausage tongue bacon boudin pork loin. Porchetta filet mignon pig jowl, pastrami doner kielbasa ham hock pork chop bacon chicken short ribs meatloaf.
Beef ribs pork meatball, drumstick pig burgdoggen prosciutto spare ribs porchetta alcatra chicken jowl venison frankfurter. Tongue sausage drumstick picanha beef pig jerky, meatball ham. Ribeye cow meatloaf, ham spare ribs pancetta tri-tip capicola kevin bresaola shank. Cupim pork loin capicola prosciutto, ham beef t-bone tail biltong jerky filet mignon flank pastrami bresaola turducken.
Bacon cow venison doner short ribs. Strip steak salami landjaeger capicola. Ground round turducken chicken strip steak flank, sausage bacon shank. Short ribs jerky leberkas corned beef tenderloin t-bone beef ribs tongue chicken pancetta kevin flank fatback sausage. Shoulder beef ribs fatback bacon, tongue venison burgdoggen meatloaf t-bone ham hock doner chicken kevin. Drumstick andouille cow shankle. Short loin corned beef bresaola meatball cupim, strip steak t-bone.
</p>
<script>/*
* smoothscroll polyfill - v0.3.5
* https://iamdustan.github.io/smoothscroll
* 2016 (c) Dustan Kasten, Jeremias Menichelli - MIT License
*/
(function(w, d, undefined) {
'use strict';
/*
* aliases
* w: window global object
* d: document
* undefined: undefined
*/
// polyfill
function polyfill() {
// return when scrollBehavior interface is supported
if ('scrollBehavior' in d.documentElement.style) {
return;
}
/*
* globals
*/
var Element = w.HTMLElement || w.Element;
var SCROLL_TIME = 468;
/*
* object gathering original scroll methods
*/
var original = {
scroll: w.scroll || w.scrollTo,
scrollBy: w.scrollBy,
elScroll: Element.prototype.scroll || scrollElement,
scrollIntoView: Element.prototype.scrollIntoView
};
/*
* define timing method
*/
var now = w.performance && w.performance.now
? w.performance.now.bind(w.performance) : Date.now;
/**
* changes scroll position inside an element
* @method scrollElement
* @param {Number} x
* @param {Number} y
*/
function scrollElement(x, y) {
this.scrollLeft = x;
this.scrollTop = y;
}
/**
* returns result of applying ease math function to a number
* @method ease
* @param {Number} k
* @returns {Number}
*/
function ease(k) {
return 0.5 * (1 - Math.cos(Math.PI * k));
}
/**
* indicates if a smooth behavior should be applied
* @method shouldBailOut
* @param {Number|Object} x
* @returns {Boolean}
*/
function shouldBailOut(x) {
if (typeof x !== 'object'
|| x === null
|| x.behavior === undefined
|| x.behavior === 'auto'
|| x.behavior === 'instant') {
// first arg not an object/null
// or behavior is auto, instant or undefined
return true;
}
if (typeof x === 'object'
&& x.behavior === 'smooth') {
// first argument is an object and behavior is smooth
return false;
}
// throw error when behavior is not supported
throw new TypeError('behavior not valid');
}
/**
* finds scrollable parent of an element
* @method findScrollableParent
* @param {Node} el
* @returns {Node} el
*/
function findScrollableParent(el) {
var isBody;
var hasScrollableSpace;
var hasVisibleOverflow;
do {
el = el.parentNode;
// set condition variables
isBody = el === d.body;
hasScrollableSpace =
el.clientHeight < el.scrollHeight ||
el.clientWidth < el.scrollWidth;
hasVisibleOverflow =
w.getComputedStyle(el, null).overflow === 'visible';
} while (!isBody && !(hasScrollableSpace && !hasVisibleOverflow));
isBody = hasScrollableSpace = hasVisibleOverflow = null;
return el;
}
/**
* self invoked function that, given a context, steps through scrolling
* @method step
* @param {Object} context
*/
function step(context) {
var time = now();
var value;
var currentX;
var currentY;
var elapsed = (time - context.startTime) / SCROLL_TIME;
// avoid elapsed times higher than one
elapsed = elapsed > 1 ? 1 : elapsed;
// apply easing to elapsed time
value = ease(elapsed);
currentX = context.startX + (context.x - context.startX) * value;
currentY = context.startY + (context.y - context.startY) * value;
context.method.call(context.scrollable, currentX, currentY);
// scroll more if we have not reached our destination
if (currentX !== context.x || currentY !== context.y) {
w.requestAnimationFrame(step.bind(w, context));
}
}
/**
* scrolls window with a smooth behavior
* @method smoothScroll
* @param {Object|Node} el
* @param {Number} x
* @param {Number} y
*/
function smoothScroll(el, x, y) {
var scrollable;
var startX;
var startY;
var method;
var startTime = now();
// define scroll context
if (el === d.body) {
scrollable = w;
startX = w.scrollX || w.pageXOffset;
startY = w.scrollY || w.pageYOffset;
method = original.scroll;
} else {
scrollable = el;
startX = el.scrollLeft;
startY = el.scrollTop;
method = scrollElement;
}
// scroll looping over a frame
step({
scrollable: scrollable,
method: method,
startTime: startTime,
startX: startX,
startY: startY,
x: x,
y: y
});
}
/*
* ORIGINAL METHODS OVERRIDES
*/
// w.scroll and w.scrollTo
w.scroll = w.scrollTo = function() {
// avoid smooth behavior if not required
if (shouldBailOut(arguments[0])) {
original.scroll.call(
w,
arguments[0].left || arguments[0],
arguments[0].top || arguments[1]
);
return;
}
// LET THE SMOOTHNESS BEGIN!
smoothScroll.call(
w,
d.body,
~~arguments[0].left,
~~arguments[0].top
);
};
// w.scrollBy
w.scrollBy = function() {
// avoid smooth behavior if not required
if (shouldBailOut(arguments[0])) {
original.scrollBy.call(
w,
arguments[0].left || arguments[0],
arguments[0].top || arguments[1]
);
return;
}
// LET THE SMOOTHNESS BEGIN!
smoothScroll.call(
w,
d.body,
~~arguments[0].left + (w.scrollX || w.pageXOffset),
~~arguments[0].top + (w.scrollY || w.pageYOffset)
);
};
// Element.prototype.scroll and Element.prototype.scrollTo
Element.prototype.scroll = Element.prototype.scrollTo = function() {
// avoid smooth behavior if not required
if (shouldBailOut(arguments[0])) {
original.elScroll.call(
this,
arguments[0].left || arguments[0],
arguments[0].top || arguments[1]
);
return;
}
// LET THE SMOOTHNESS BEGIN!
smoothScroll.call(
this,
this,
arguments[0].left,
arguments[0].top
);
};
// Element.prototype.scrollBy
Element.prototype.scrollBy = function() {
var arg0 = arguments[0];
if (typeof arg0 === 'object') {
this.scroll({
left: arg0.left + this.scrollLeft,
top: arg0.top + this.scrollTop,
behavior: arg0.behavior
});
} else {
this.scroll(
this.scrollLeft + arg0,
this.scrollTop + arguments[1]
);
}
};
// Element.prototype.scrollIntoView
Element.prototype.scrollIntoView = function() {
// avoid smooth behavior if not required
if (shouldBailOut(arguments[0])) {
original.scrollIntoView.call(this, arguments[0] || true);
return;
}
// LET THE SMOOTHNESS BEGIN!
var scrollableParent = findScrollableParent(this);
var parentRects = scrollableParent.getBoundingClientRect();
var clientRects = this.getBoundingClientRect();
if (scrollableParent !== d.body) {
// reveal element inside parent
smoothScroll.call(
this,
scrollableParent,
scrollableParent.scrollLeft + clientRects.left - parentRects.left,
scrollableParent.scrollTop + clientRects.top - parentRects.top
);
// reveal parent in viewport
w.scrollBy({
left: parentRects.left,
top: parentRects.top,
behavior: 'smooth'
});
} else {
// reveal element in viewport
w.scrollBy({
left: clientRects.left,
top: clientRects.top,
behavior: 'smooth'
});
}
};
}
if (typeof exports === 'object') {
// commonjs
module.exports = { polyfill: polyfill };
} else {
// global
polyfill();
}
})(window, document);</script>
答案 2 :(得分:0)
您可以将CSS属性scroll-behavior
设置为smooth
,以便单击锚标记将平滑滚动到该元素。
html, body{
scroll-behavior: smooth;
}
a, a:visited{
color: initial;
}
<a href="#elem">Scroll To Element</a>
<div id="elem" style="margin: 500px 0px;">Div</div>
您可以将for循环与window.scrollTo和setTimeout一起使用,以使用纯Javascript平滑滚动。要滚动到特定元素,只需使用该元素的offsetTop作为第一个参数调用scrollToSmoothly函数即可。
function scrollToSmoothly(pos, time) {
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
if (isNaN(pos)) {
throw "Position must be a number";
}
if (pos < 0) {
throw "Position can not be negative";
}
var currentPos = window.scrollY || window.screenTop;
if (currentPos < pos) {
var t = 10;
for (let i = currentPos; i <= pos; i += 10) {
t += 10;
setTimeout(function() {
window.scrollTo(0, i);
}, t / 2);
}
} else {
time = time || 2;
var i = currentPos;
var x;
x = setInterval(function() {
window.scrollTo(0, i);
i -= 10;
if (i <= pos) {
clearInterval(x);
}
}, time);
}
}
<button onClick="scrollToDiv()">Scroll To Element</button>
<div style="margin: 1000px 0px; text-align: center;">Div element<p/>
<button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button>
<p/>
<button onClick="scrollToSmoothly(document.body.offsetHeight)">
Scroll To Bottom
</button>
</div>
<button onClick="scrollToSmoothly(Number(500))">
Scroll to y-position 500px
</button>
<script>
function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
if(isNaN(pos)){
throw "Position must be a number";
}
if(pos<0){
throw "Position can not be negative";
}
var currentPos = window.scrollY||window.screenTop;
if(currentPos<pos){
if(time){
var x;
var i = currentPos;
x = setInterval(function(){
window.scrollTo(0, i);
i += 10;
if(i>=pos){
clearInterval(x);
}
}, time);
} else {
var t = 10;
for(let i = currentPos; i <= pos; i+=10){
t+=10;
setTimeout(function(){
window.scrollTo(0, i);
}, t/2);
}
}
} else {
time = time || 2;
var i = currentPos;
var x;
x = setInterval(function(){
window.scrollTo(0, i);
i -= 10;
if(i<=pos){
clearInterval(x);
}
}, time);
}
}
function scrollToDiv(){
var elem = document.querySelector("div");
scrollToSmoothly(elem.offsetTop);
}
</script>