admin管理员组文章数量:1419251
I have the following script that provides an anchor effect:
// Smooth scrolling when clicking on a hash link
$('a[href*="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
if ($(window).width() > 1023) {
var $scrollTop = $target.offset().top - 120;
} else {
var $scrollTop = $target.offset().top;
}
$('html, body').stop().animate({
'scrollTop': $scrollTop
}, 900, 'swing');
});
The problem is that this only works on home page, but in the other pages it does not work because I need to provide the web link (www.url/#anchor). But if I do this, the effect does not apply. someone knows how to add to the effect, for example get_site_url ('/#anchor/');
, and so this always take the url of the web as a base?
I hope I have expressed myself well. Greetings and thanks
I have the following script that provides an anchor effect:
// Smooth scrolling when clicking on a hash link
$('a[href*="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
if ($(window).width() > 1023) {
var $scrollTop = $target.offset().top - 120;
} else {
var $scrollTop = $target.offset().top;
}
$('html, body').stop().animate({
'scrollTop': $scrollTop
}, 900, 'swing');
});
The problem is that this only works on home page, but in the other pages it does not work because I need to provide the web link (www.url/#anchor). But if I do this, the effect does not apply. someone knows how to add to the effect, for example get_site_url ('/#anchor/');
, and so this always take the url of the web as a base?
I hope I have expressed myself well. Greetings and thanks
Share Improve this question asked Jul 24, 2019 at 10:52 Dario B.Dario B. 15510 bronze badges1 Answer
Reset to default 1CSS now has the property scroll-behavior
(browser support is there but not so great). You can use it as described here:
html { scroll-behavior: smooth; } @media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
If this doesn't work for you, you're stuck with JS. The problem is, on a new page load, browsers automatically jump to the position of the fragment. But there is a workaround as described in this StackOverflow answer:
// to top right away if (window.location.hash) scroll(0,0); // void some browsers issue setTimeout(function() { scroll(0,0); }, 1); $(function() { // *only* if we have anchor on the url if(window.location.hash) { // smooth scroll to the anchor id $('html, body').animate({ scrollTop: $(window.location.hash).offset().top + 'px' }, 1000, 'swing'); } });
本文标签: menusjquery anchor effect does not work properly
版权声明:本文标题:menus - jquery anchor effect does not work properly 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745299270a2652272.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论