我需要一个项目的帮助。我的网站上有一个“评论”部分,当用户滚动到某个点并执行以下操作时,我想显示一个按钮:
#comments
到达视口的顶部,并且innerHTML = 'LEAVE A REVIEW'
#review_form
使用scrollIntoView()
方法滚动到视图中。#review_form
div,浏览器将认识到#review_form
div现在位于浏览器视口的顶部,它将LEAVE A REVIEW
更改为SCROLL TO TOP
onClick
功能从scrollIntoView()
更改为实际上滚动到页面顶部。我的问题是,我是否要使用以下代码正确处理? else if
语句不起作用。我也不知道如何更改按钮的onClick
。
我需要创建两个单独的<button>
吗?
HTML:
<button onClick="scrollToComment()" id="scroll-btn"></button>
<div id="comments">
//a bunch of reviews and comments go here
</div>
<div id="review_form">
//review form here
</div>
JS:
window.addEventListener('scroll', function() {
const comments = document.querySelector('#comments');
const commentsPosition = comments.getBoundingClientRect();
const scrollBtn = document.querySelector('#scroll-btn');
const review = document.querySelector('#review_form');
const reviewPosition = review.getBoundingClientRect();
if( commentsPosition.top < -1 && commentsPosition.top < 1 ) {
scrollBtn.style.display = 'block';
document.getElementById('scroll-btn').innerHTML = 'LEAVE A REVIEW';
}
else if( reviewPosition.top < -1 && reviewPosition.top < 1 ) {
//not working:
document.getElementById('scroll-btn').innerHTML = 'BACK TO TOP';
}
else {
scrollBtn.style.display = 'none';
}
});
// scroll to review form
function scrollToComment() {
var button = document.querySelector('#review_form');
button.scrollIntoView();
}
首先,您的if条件很奇怪:if( commentsPosition.top < -1 && commentsPosition.top < 1 )
;
如果commentsPosition.top
小于-1,它也小于1,因此不需要&& commentsPosition.top < 1
这部分。
[现在,考虑到#review_form
在HTML中的#comments
之后,我假设您的评论表单位于注释部分的下方。因此,无法访问您的else if
块,因为如果您的else if
为true,则意味着您的if
也为true。如果您的if
为假,那么您的else if
也为假。
这是您可以看的第一点。