根据屏幕位置更改InnerHTML吗?

问题描述 投票:0回答:1

我需要一个项目的帮助。我的网站上有一个“评论”部分,当用户滚动到某个点并执行以下操作时,我想显示一个按钮:

  1. [按钮显示何时#comments到达视口的顶部,并且innerHTML = 'LEAVE A REVIEW'
  2. [当用户单击按钮时,#review_form使用scrollIntoView()方法滚动到视图中。
  3. [这会将用户带到#review_form div,浏览器将认识到#review_form div现在位于浏览器视口的顶部,它将LEAVE A REVIEW更改为SCROLL TO TOP
  4. 我还没到这里,但是我想将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();

}
javascript html
1个回答
0
投票

首先,您的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也为假。

这是您可以看的第一点。

© www.soinside.com 2019 - 2024. All rights reserved.