javascript - 为什么scrollTop没有反应?

标签 javascript jquery

页面上的其他 jQuery 脚本工作正常,只是滚动顶部不行,我什至可以让它在 https://jsfiddle.net/ivolong/tyvusdte/ 上工作。只是不在我的网站上,该网站使用 JQuery 3.2.1。

在正文中的脚本标记之间我有:

$("#button1").click(function() {
        $('html, body').animate({
            scrollTop: $("#slide2").offset().top
        }, 3000);
    });


    $("#button2").click(function() {
        $('html, body').animate({
            scrollTop: $("#slide1").offset().top
        }, 3000);
    });

然后我有:

<div class="slide" id="slide1">

        <p id="title">Title</p>

        <div id="specialText">

            <p>Line 1.</p>
            <p>Line 2.</p>
            <p>Line 3.</p>
            <p>Line 4.</p>

        </div>

        <button class="button" id="button1">&#8595;</button>

    </div>

    <div class="slide" id="slide2">

        <p id="title">Title</p>

        <div id="text">

            <p>Line 5.</p>
            <p>Line 6.</p>
            <p>Line 7.</p>
            <p>Line 8.</p>

        </div>

        <button class="button" id="button2">&#8595;</button>

    </div>

但是点击按钮时没有响应

最佳答案

这是因为javascript代码位于html代码之上。此时,当解释 JavaScript 代码时,不会呈现任何按钮,这会导致没有附加事件处理程序。

您可以通过将 javascript 代码放置在 html 代码下来解决此问题,或者像下面提到的评论中那样正确:将您的代码包装在 jQueries document.ready 函数中,如下所示:

$(document).ready(function() {
    $("#button1").click(function() {
        $('html, body').animate({
            scrollTop: $("#slide2").offset().top
        }, 3000);
    });

    $("#button2").click(function() {
        $('html, body').animate({
            scrollTop: $("#slide1").offset().top
        }, 3000);
    });
});

关于javascript - 为什么scrollTop没有反应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46433402/

相关文章:

javascript - 为什么在 Chrome 中使用 Panzoom 模糊 SVG 元素?

javascript - 1 个带有 1 个输入字段和 2 个按钮的表单;需要根据使用的按钮更改输入名称

javascript - 如何使用Ctrl+f同时搜索下拉列表和网页内容?

jquery tokenInput如何将ajax调用url动态更改为脚本

javascript - 3d.js(强制)- 获取工具提示链接上的当前鼠标位置

javascript - ajax net::ERR_EMPTY_RESPONSE 等待响应 2 分钟后 - node.js 服务器

javascript - 在另一个 ViewComponent 中调用一个 ViewComponent

jquery - ASP.NET MVC3 清晰表单

javascript - 带有 :contains condition 的 switch 语句

javascript - 如何停止提交输入中的空字段