[英]Scroll to top button showing when not on top of the page
我想使用 angular bootstrap 在我的頁面中固定滾動到頂部箭頭。 目前我有
<div class="col-md-1">
<div class="affix">
<div>
<a th:href="@{/}" href="#" target="_self"><img id="image" src="source" alt="yoli" width="50px" /></a>
</div>
<a href="#search-bar">Scroll to top</a>
</div>
</div>
<div class="col-md-6">
<div id="search-bar" ng-include="blabla"></div>
<li ng-repeat="something"></li>
</div>
但是,當單擊“滾動到頂部”時,它僅在第一次起作用,因為 url 更改為 ...#search-bar,當您再次單擊它時,沒有任何反應。 那么如何在不更改 url 的情況下滾動到頂部?
並詢問如何使“滾動到頂部”僅在搜索欄未顯示時顯示?
我正在考慮使用 $anchorScroll 並在 li 上使用 id 編號,如果它高於“element-3”,則顯示按鈕,但不確定這是否可行。
更新:我正在考慮遵循這個例子,即使用導航欄,即#search 和#results,並使#search href 在#results 上可見,而#results 則隱藏。
您也可以在沒有 jQuery 的情況下執行此操作:
function filterPath(string) {
return string
.replace(/^\//, '')
.replace(/(index|default).[a-zA-Z]{3,4}$/, '')
.replace(/\/$/, '');
}
const locationPath = filterPath(location.pathname);
document.querySelectorAll('a[href*="#"]').forEach(link => {
let thisPath = filterPath(link.pathname) || locationPath;
if ((location.hostname == link.hostname || !link.hostname)
&& (locationPath == thisPath)
) {
let hashName = link.hash.replace(/#/, '');
if (hashName) {
let targetEl = document.getElementById(hashName);
if (targetEl) {
link.addEventListener('click', () => {
event.preventDefault();
targetEl.scrollIntoView({
top: 50,
left: 0,
behavior: "smooth"
});
});
}
}
}
});
這是您如何做到的。 創建一個按鈕:
<a href="#" class="scrollToTop">Scroll To Top</a>
CSS:
.scrollToTop{
width:100px;
height:130px;
padding:10px;
text-align:center;
background: whiteSmoke;
font-weight: bold;
color: #444;
text-decoration: none;
position:fixed;
top:75px;
right:40px;
display:none;
background: url('arrow_up.png') no-repeat 0px 20px;
}
.scrollToTop:hover{
text-decoration:none;
}
JavaScript:
$(document).ready(function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.