问题描述
我正在尝试制作一个按钮,当按下到表单的最后一个“帖子”/最后一篇文章时,该按钮可以自动滚动。我试过按百分比滚动,但它不起作用,因为并非每个帖子都具有相同的高度。 现在我明白了一个更好的方法是滚动到最后一篇文章/last-child,但我不知道该怎么做。
所以,我得到了这个按钮:
<button type='button' id='lastPost' class='ipsButton bigIcon_button' data-ipsTooltip title='Go to the last comment'><i class="fas fa-fast-forward"></i></button>
我得到了这样的表格:
<form action="https://lsgamerz.net/topic/7234-inside-project-lsgamerz-juliano-dillon-new-theme/?csrfKey=d74832284f92e0bdec551b0d50803919&do=multimodComment" method="post" data-ipspageaction="" data-role="moderationTools"></form>
还有更多这样的文章:
<article id="elComment_34910" class="cPost ipsBox ipsResponsive_pull ipsComment ipsComment_parent ipsClearfix ipsClear ipsColumns ipsColumns_noSpacing ipsColumns_collapsePhone "></article>
因此,如您所见,我没有表单的类或 id,文章 id 是动态变化的。我以前从未使用过 Javascript,我仍然后悔没有学习它,因为现在我被这些小东西困住了。
如果你能帮我写一个代码,当你按下按钮时,它会向下滚动到表单的最后一篇文章,留下回复。我已经搜索了所有互联网,但它对我不起作用,我尝试了 20 种不同的代码,但仍然无法滚动到我想要的位置)。
解决方法
您可以通过此滚动到表单的最后一篇文章。
$(document).on('click','#lastPost',function () {
var form= document.getElementById("your_form_id");
form.scrollTop = form.scrollHeight;
})
,
只是一个想法,您可以在最后一篇文章的周围或上方放置一个空元素,该元素具有恒定的已知 ID,并使您的“按钮”成为一个链接,该链接只是指向其他元素的 href。不需要 JavaScript。
<!-- Give the below link button styling (make it look like a button -->
<a href="#lastarticle" class='ipsButton bigIcon_button'>Skip To Last Comment<i class="fas fa-fast-forward"></i></a>
<!--
Your form,other articles,whatever is in between the button and the last article
...
...
-->
<div id="lastarticle"></div> <!-- Empty div that takes up no space,can also wrap the last article,if you'd like -->
<article id="elComment_34910" class="cPost ipsBox ipsResponsive_pull ipsComment ipsComment_parent ipsClearfix ipsClear ipsColumns ipsColumns_noSpacing ipsColumns_collapsePhone "></article> <!-- the last article -->
如果您想使用 JavaScript 解决问题,请尝试获取 html 文档中的所有文章,选择最后一篇,然后滚动到它。见下文。
function skipToLast(){
// Get all elements with article tag
var articles = document.getElementsByTagName('article');
// Get the last article
var lastArticle = articles[articles.length-1];
// Scroll to that last article
lastArticle.scrollIntoView();
}
<!-- Add onclick="skipToLast()" to have the button call your JS function -->
<button onclick="skipToLast()" type='button' id='lastPost' class='ipsButton bigIcon_button' data-ipsTooltip title='Go to the last comment'><i class="fas fa-fast-forward"></i></button>
试试这个。 制作了一个使用 scrollIntoView() 方法的函数。 该函数抓取所有文章,然后选择最后一篇,然后使用 ScrollIntoView() 方法。
希望这对你有用!
//Button where you can place at the top of the page.
<input type="Button" onclick="lastArticle()" value="Press me for last article"/>
//Code you put in a JS file och between script tags
const lastArticle = function () {
const btn = document.querySelectorAll("article");
const anchor = btn[btn.length - 1].scrollIntoView();
};
例如,这是一个 JSfiddle 链接。 https://jsfiddle.net/f8s3t67w/