javascript - 根据屏幕位置更改 InnerHTML?
问题描述
我需要一个项目的帮助。我有我们网站的评论部分,我希望在用户滚动到某个点并执行以下操作时显示一个按钮:
- 按钮在
#comments
到达视口顶部时显示,并且innerHTML = 'LEAVE A REVIEW'
- 当用户单击按钮时,
#review_form
使用方法滚动到视图中scrollIntoView()
。 - 这会将用户带到
#review_form
浏览器将识别的#review_form
div 现在位于浏览器视口的顶部,它将更改LEAVE A REVIEW
为SCROLL TO TOP
- 我还没有到这里,但我想将
onClick
功能从scrollIntoView()
实际滚动到页面顶部。
我的问题是,我是否使用以下代码以正确的方式进行此操作?该else if
声明不起作用。我也不知道如何更改onClick
按钮的。
我需要创建两个单独<button>
的 s 吗?
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
是#comments
在您的 HTML 之后,我假设您的评论表单位于您的评论部分下方。所以你的else if
块无法到达,因为如果你else if
是真的,那意味着你if
也是真的。如果你if
是假的,那么你else if
也是假的。
这是你可以看到的第一点。
如果您想动态更改您的点击功能,您可以这样做并从您的 html 中删除 onClick:
const scrollBtn = document.querySelector('#scroll-btn');
scrollBtn.addEventListener('click', () => {
if(condition){
//scroll to review form
} else if (condition){
//scroll to top
}
}
);
推荐阅读
- android - 如何使用泛型或反射来显示/隐藏片段?Kotlin 安卓
- reactjs - 我的 .png 图像 PUT 请求到 AWS S3 存储桶显示为文本
- javascript - 在 javascript 中从 ajax 调用 PHP
- list - 如何创建名为“dir”命令列出的文件的 txt 文件?
- flutter - 如何使flutter中的文本字段可以插入图像
- asp.net-core - 如何使用 Angular(样板)在 Asp Dot Net Core 中的 Facebook 页面上自动发布提要?
- html - CSS位置相对于div的前50%不起作用
- gridview - Flutter 如何在网格视图中显示图库图像
- java - 获取 Firebase 数据库中的最后一个节点
- selenium - 自动完成部分硒