如何创建一个jQuery函数,使点击的按钮会滚动到下一个日期。

huangapple go评论126阅读模式
英文:

How do I create a jquery function so that a clicked button will scroll to the next date

问题

我有一个带有类名 'next' 的触发按钮,并编写了以下 jQuery 函数:

  1. $(document).ready(function () {
  2. $(".next").click(function (e) {
  3. e.preventDefault();
  4. console.log('got here');
  5. var currentDate = new Date();
  6. console.log(currentDate);
  7. var dateElements = $(".date");
  8. var nextDateElement = null;
  9. dateElements.each(function () {
  10. var date = new Date($(this).text());
  11. if (date > currentDate) {
  12. nextDateElement = $(this);
  13. return false; // 退出循环
  14. }
  15. });
  16. if (nextDateElement) {
  17. $('html, body').animate({
  18. scrollTop: nextDateElement.offset().top
  19. }, 'slow');
  20. }
  21. });
  22. });

但是它无法正常工作,甚至无法显示控制台日志。我可能做错了什么?

英文:

I have a trigger button with a class of 'next'and I have coded a jquery function as follows:

  1. $(document).ready(function () {
  2. $(".next").click(function (e) {
  3. e.preventDefault();
  4. console.log('got here');
  5. var currentDate = new Date();
  6. console.log(currentDate);
  7. var dateElements = $(".date");
  8. var nextDateElement = null;
  9. dateElements.each(function () {
  10. var date = new Date($(this).text());
  11. if (date > currentDate) {
  12. nextDateElement = $(this);
  13. return false; // Exit the loop
  14. }
  15. });
  16. if (nextDateElement) {
  17. $('html, body').animate({
  18. scrollTop: nextDateElement.offset().top
  19. }, 'slow');
  20. }
  21. });
  22. });

but I can't get it to work - or even display the console log. What might I be doing wrong?

答案1

得分: 1

需要添加一些额外的填充吗?"Offset" 定义了元素的顶部位置。尝试这样做:

  1. scrollTop: nextDateElement.offset().top + 100

其他尝试的事项:

  1. 确认你的逻辑是否正确。使用控制台记录所有日期,以确保它们符合你的预期。

  2. 尝试不使用动画效果:

  1. $('html').scrollTop(nextDateElement.offset());
英文:

Do you need to add some additional padding? Offset defines the top of the element. Try this:

  1. scrollTop: nextDateElement.offset().top + 100

Other things to try:

  1. Confirm your logic is correct. console log all the dates to make sure they're what you expect.

  2. Try it without animate

  1. $('html').scrollTop( nextDateElement.offset() );

huangapple
  • 本文由 发表于 2023年8月11日 01:24:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定