JQuery滚动事件无法正常工作

时间:2014-08-04 19:42:32

标签: javascript jquery html scroll

我一直尝试使用按钮点击在文本框中制作jquery滚动文本,但它在IE,Chrome或Firefox中无效。

我希望我的文本框能够在点击按钮时向下滚动。

<!DOCTYPE html>
<html>
<head>
    <script src="http://localhost:62240/Scripts/jquery-2.1.1.js"></script>
    <script>
        x = 0;
        $(document).ready(function () {
            $("div").scroll(function () {
                $("span").text(x += 1);
            });
            $("button").click(function () {
                $("div").scroll();
            });
        });
    </script>
</head>
<body>

    <p>Try the scrollbar in the div</p>
    <div style="border:1px solid black;width:200px;height:100px;overflow:scroll;">
        In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
        <br><br>
        'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
    </div>
    <p>Scrolled <span>0</span> times.</p>
    <button>Trigger scroll event for the window</button>

</body>
</html>

Demo

3 个答案:

答案 0 :(得分:2)

scroll()是滚动div时触发的事件。如果要通过单击按钮进行滚动,请尝试改为:

    x = 0;
    $(document).ready(function () {
        $("button").click(function () {
            $('div').animate({ scrollTop: (x+1)*20 }, 200);
            $("span").text(x += 1);
        });
    });

FIDDLE DEMO

答案 1 :(得分:0)

您的jquery导入无效。如果您使用完全相同的代码,请将其粘贴到jsfiddle中,并使用它们导入的jquery,然后单击按钮,跨度计数器将递增。

答案 2 :(得分:0)

这是@lpg修复的代码,以使一切正常工作(对不起,我写这个作为答案,我还没有足够的声誉来评论):

    x = 0;
    height = 0;
    $(document).ready(function () {
        $("button").click(function () {
            height = $('div').scrollTop();
            $('div').animate({ scrollTop: height+20 }, 200);
        });
        $('div').scroll(function() {
            $("span").text(x += 1);
        });
    });

以下是JS Fiddle demo已修复。

jQuery方法element.scrollTop();用于获取可滚动元素的滚动位置,并在包含参数时设置它。然后$('div').scrollTop();返回div顶部滚动的像素,$('div').scrollTop(20);将从顶部滚动div 20像素。

相关问题