[英]How to use smooth scrolling for Javascript?
I came across a smooth scrolling function from JavaScript as shown here.我在 JavaScript 中遇到了平滑滚动功能,如下所示。
// 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
};
});
}
}
});
I currently have a website coded using HTML and CSS.我目前有一个使用 HTML 和 CSS 编码的网站。 How do I implement the javascript function into it?如何在其中实现 javascript 功能? I've tried googling it , but the answers are always not specfic enough as I'm really new at this.我试过用谷歌搜索它,但答案总是不够具体,因为我真的很陌生。
Help would be much appreciated!帮助将不胜感激!
for simple javascript its as easy as adding a script tag into your html head对于简单的 javascript,就像在你的 html 头中添加一个脚本标签一样简单
<head>
<title>:D</title>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
//your javascript here
</script>
</head>
There are of course more ways to achieve this - for more information https://www.w3schools.com/js/js_whereto.asp当然还有更多方法可以实现这一点 - 有关更多信息https://www.w3schools.com/js/js_whereto.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.