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

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

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

问题

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

$(document).ready(function () {
    $(".next").click(function (e) {
        e.preventDefault();
        console.log('got here');
        var currentDate = new Date();
        console.log(currentDate);
        var dateElements = $(".date");

        var nextDateElement = null;
        dateElements.each(function () {
            var date = new Date($(this).text());
            if (date > currentDate) {
                nextDateElement = $(this);
                return false; // 退出循环
            }
        });

        if (nextDateElement) {
            $('html, body').animate({
                scrollTop: nextDateElement.offset().top
            }, 'slow');
        }
    });
});

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

英文:

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

$(document).ready(function () {
    $(".next").click(function (e) {
        e.preventDefault();
        console.log('got here');
        var currentDate = new Date();
        console.log(currentDate);
        var dateElements = $(".date");

        var nextDateElement = null;
        dateElements.each(function () {
            var date = new Date($(this).text());
            if (date > currentDate) {
                nextDateElement = $(this);
                return false; // Exit the loop
            }
        });

        if (nextDateElement) {
            $('html, body').animate({
                scrollTop: nextDateElement.offset().top
            }, 'slow');
        }
    });
});

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

答案1

得分: 1

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

scrollTop: nextDateElement.offset().top + 100

其他尝试的事项:

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

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

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

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

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

$('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:

确定