我有此js,但随后在页面完成加载之前开始滚动。有没有办法检查页面加载,然后加载该平滑效果?
jQuery(document).ready(function(){
var href = window.location.href+'#team';
var splitit = (href.split('#'))[1];
if(splitit !== "" || splitit !== "undefined"){
jQuery('html, body').animate({
scrollTop: jQuery('#'+splitit).offset().top - 50
}, 2000);
}
});
另外,splitit
做什么?我们可以删除它吗?
split((方法用于将字符串拆分为一个子字符串,并返回新数组。
var str = "How are you doing today?";
var res = str.split(" ");
//result is array [How,are,you,doing,today?]
删除什么?检查所需的拆分位置是在url'#' - 符号或"#"之后没有空的URL。
尝试完成页面时运行的加载事件,包括图形。
jQuery( window ).load(function() {
// Run code
});
对于此功能,您可以使用现代浏览器CSS:
html {
scroll-behavior: smooth;
}
在 function smoothScroll(){
// this part will add ID's to the named anchor tags
// please name tags names not to interfere with other elements id's but
// also will look good in addressbar, as : #ListOfFeaturedProductsSection
$("a").each(function(){
var t=this;
if (t.name!=="" && t.id==""){
t.id=t.name;
}
});
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
var hash = this.hash;
if (hash) {
event.preventDefault();
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
}
}
});
}
splitit是目标的ID属性。
实际上,很明显如何检查所有资源都已加载,但是您可以将此jQuery代码放在页面末尾,我认为这对您有所帮助。