[英]Go to top of the page before opening link in the same window(tab). How to?
I want to go to top of the page when click on link and then open link in the same tab 单击链接然后在同一选项卡中打开链接时,我想转到页面顶部
I tried to use this code, but I only go to top of the page and link doesnt open 我尝试使用此代码,但是我仅转到页面顶部,并且链接未打开
This is my JS 这是我的JS
$(document).ready(function(){
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},1800);
return false;
});
});
And this is my HTML link 这是我的HTML链接
<a href="./current_page?page=5" class="scrollToTop">></a>
Please help) 请帮忙)
Try this 尝试这个
$(document).ready(function(){
$('.scrollToTop').click(function(){
const url = $(this).attr('href');
$('html, body').animate({scrollTop : 0}, 1800, function() {
window.open(url);
});
return false;
});
});
One way to achieve this is to execute page navigation via JavaScript, after the scroll to top animation has completed. 实现此目的的一种方法是在滚动到顶部动画之后,通过JavaScript执行页面导航。
This can be done by navigating the broswer during the .promise().done( .. )
callback, where you'd update the location
to the href of the clicked link: 这可以通过在.promise().done( .. )
回调期间浏览浏览器来完成,在该回调中,您将location
更新为单击链接的href:
$(document).ready(function() { $('.scrollToTop').click(function() { /* Obtain href from clicked link element */ const href = $(this).attr('href'); $('html, body').animate({ scrollTop: 0 }, 1800) .promise() .done(function() { /* After animation complete, navigate to link's href */ location = href; console.log(`Navigate: ${href} (won't work in stack overflow sandbox)`); }); return false; }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <h1>Scroll past</h1> <h1>Scroll past</h1> <h1>Scroll past</h1> <h1>Scroll past</h1> <a href="./current_page?page=5" class="scrollToTop">Scroll to top, then navigate ></a>
Since your click
event Is returning false
the href
tag of your anchor won't redirect. 由于您的click
事件返回false
,因此您锚点的href
标记将不会重定向。
Note that since you are changing routes through an anchor the loaded page will always start at the top of the body. 请注意,由于您正在更改通过锚点的路线,因此加载的页面将始终从正文的顶部开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.