jQuery 滚动到元素然后单击它

jQuery scroll to element and then click it

我目前正在尝试 jQuery 滚动到一个元素(在本例中为手风琴项),然后我希望它自动打开(单击)。到目前为止,我可以通过 jquery 动画成功滚动到该项目,但我似乎无法弄清楚如何在动画功能完成后单击它。到目前为止,这是我的代码:

$([document.documentElement, document.body]).animate({
            scrollTop: $("#"+ articleID +"").offset().top
        }, 800).then(function(){
            $("div[id='"+ articleID +"']").click();
        });

变量被定义为函数参数,但函数的其余部分与问题无关。

上面的代码成功滚动到所需的元素,但之后不会点击它。有什么想法可以解决这个问题吗?

.then() is a promise chain. Since animate() 不会 return 承诺,因此它不会按预期工作。如果你想在某个动画发生后执行一个动作,你应该给它传递 complete 回调函数。

所以你的最终代码应该是这样的:

$([document.documentElement, document.body]).animate({// The selector should be $(document.documentElement) otherwise it will trigger the click event twice.
  scrollTop: $("#" + articleID + "").offset().top
}, 800, function() {
  $("div[id='" + articleID + "']").click();
});

注意: 正如@freedomn-m 指出的那样,应该只有一个选择器用于传递 animate() 函数。所以你应该用 $(document.documentElement).

替换 $([document.documentElement, document.body])

我提出了一个解决方法。

var t = 800;
 $([document.documentElement, document.body]).animate({
        scrollTop: $("#"+ articleID +"").offset().top
    }, t);
 setTimeout(function(){
    $("div[id='" + articleID + "']").click();
 }, t);