首页 > 解决方案 > 根据屏幕位置更改 InnerHTML?

问题描述

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

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

}

标签: javascripthtml

解决方案


首先,您的 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
    }
  }
);


推荐阅读