代码实现
jQuery 实现锚链接捕捉并平滑滚动
代码语言:javascript
复制$(document).ready(function() {
if (
typeof window.getComputedStyle(document.body).scrollBehavior === "undefined"
) {
//判断浏览器是否支持scroll-behavior
$("a.article").click(
//给class为article的a标签赋予点击事件
function() {
$("html,body").animate(
//令窗口滚动
{ scrollTop: $($(this).attr("href")).offset().top }, //滚动到当前点击的a标签的锚链接对应的位置
{ duration: 500, easing: "swing" } //滚动时间和滚动效果
);
return false;
}
);
}
});
scroll_to(Yposition) 平滑滚动函数
代码语言:javascript
复制function scroll_to(Yposition) {
if (
typeof window.getComputedStyle(document.body).scrollBehavior === "undefined"
) {
//判断浏览器是否支持scroll-behavior属性
if (!window.requestAnimationFrame) {
//判断浏览器是否支持requestAnimationFrame
window.requestAnimationFrame = function(callback) {
setTimeout(callback, 20);
}; //本质是利用setTimeout来处理scrollTo函数(js是单线程,为了避免堵塞)
} //如果不支持就手动定义(利用setTimeout)
let scrollposition = pageYOffset; //得到窗口已滚动高度
function smoothScroll() {
//数字10代表了速度的衰减率,数字越小完成滚动的时间就越少
let distance = Yposition - scrollposition;
scrollposition = scrollposition distance / 10;
if (Math.abs(distance) < 1) {
//如果距离小于1,结束递归函数
window.scrollTo(0, Yposition);
} else {
window.scrollTo(0, scrollposition);
requestAnimationFrame(smoothScroll);
}
}
requestAnimationFrame(smoothScroll); //在smoothScroll函数里递归调用,直到距离小于1
} else {
//对于支持scroll-behavior属性的浏览器,直接执行scrollTo函数
window.scrollTo(0, Yposition);
}
}
子导航栏动画
代码语言:javascript
复制function appear() {
document.getElementById("sub_navigation_bar").style.right = "10px";
setTimeout(function() {
document.getElementById("sub_navigation_bar_button").onclick = disappear;
}, 0);
}
function disappear() {
document.getElementById("sub_navigation_bar").style.right = "-150px";
setTimeout(function() {
document.getElementById("sub_navigation_bar_button").onclick = appear;
}, 0);
}
展开全文和收起全文函数
代码语言:javascript
复制function text_appear(object) {
//展开全文函数
x = object.previousSibling; //上一个节点
if (x.nodeType != 1) {
x = x.previousSibling;
}
x.style.display = "block";
y = x.previousSibling;
if (y.nodeType != 1) {
y = y.previousSibling;
}
y.style.display = "none";
object.innerHTML = "收起全文";
object.onclick = function() {
text_disappear(object);
};
}
function text_disappear(object) {
//收起全文函数
x = object.previousSibling;
if (x.nodeType != 1) {
x = x.previousSibling;
}
x.style.display = "none";
y = x.previousSibling;
if (y.nodeType != 1) {
y = y.previousSibling;
}
y.style.display = "block";
object.innerHTML = "展开全文";
object.onclick = function() {
text_appear(object);
};
}