对于使用 javascript 等进行编码相当陌生,点击滚动时出现问题,它会转到另一个 div。我已经检查了这里的很多帖子,但似乎无法找出为什么它不起作用。任何帮助将不胜感激!这可能是一个简单的修复,我只是没有经验能够注意到..
这是代码(我会尝试压缩它,但想象中间有很多内容,所以实际上值得滚动到)
HTML
<div class="button-div"><button type="button">Click here</button></div>
<div class="div-2-under-top">Content here</div>
J脚本
$("button").click(function() {
$('html,body').animate({
scrollTop: $(".div-2-under-top").offset().top},
'slow')
})
我有最新的 jquery V3.3.1,所以我认为这不会是问题......有什么想法吗?
这是实际代码本身的图片,以防万一我错过了一些重要的东西(如果代码脏了,我们深表歉意)
最佳答案
@TylerRoper 为我找到了答案。
我将把他的答案粘贴在这里,以防有人偶然发现这个问题并正在寻找答案。
OP, your button click event needs to be inside of the $(function() { ... }) section. This section will be executed after waiting for the page to load. By trying to attach an event to $("button") outside of this, the button has not loaded yet, so the event can't be attached.
关于javascript - 按钮单击滚动不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51852528/