简体   繁体   English

如何使用jQuery在页面上上下滚动?

[英]How to scroll up and down on page with jQuery?

I added a link into my page to scroll down: 我在页面中添加了一个链接以向下滚动:

<div class="scroll">
    <a onclick="scroll_down()" href="#" id="'scroll_id"> 
        click me 
    </a>
</div>

<script>
    function scroll_down() {
        var y = $(window).scrollTop(); //current position
        $("html, body").animate({scrollTop: y + $(window).height()}, 600);
    }

    function scroll_top() {
        window.scrollTo(0, 0);
    }
</script>

I want to set onclick attribute when bottom is reached to scroll_top . 当底部到达scroll_top时,我想设置onclick属性。

scroll down is working but when bottom is reached , the attribute of the onclick of <a> tag is not changed. 向下滚动有效,但是到达底部时, <a>标记的onclick属性不会更改。

<script>
    window.onscroll = function (ev) {
        if ((window.innerHeight + window.scrollY) >= $(document).height()) {
            console.log('bootom')
            $('#scroll_id').attr('onClick', '');
            $('#scroll_id').attr('onClick', 'scroll_top()');
        }
    }
</script>

do some body tell me where is the error ? 有人告诉我错误在哪里吗? why it's not working? 为什么它不起作用?

Using the on* event attributes is considered bad practice - and amending them at runtime is worse. 使用on*事件属性被认为是不好的做法-在运行时对其进行修改更糟。

A much better solution is to use a single unobtrusive event handler which determines the current scroll position of the page and moves up/down as necessary, like this: 更好的解决方案是使用单个不干扰事件处理程序,该事件处理程序确定页面的当前滚动位置并根据需要向上/向下移动,如下所示:

 $(function() { $('#scroll_id').click(function(e) { e.preventDefault(); var $win = $(window); var scrollTarget = $win.height() + $win.scrollTop() >= $(document).height() ? 0 : $win.scrollTop() + $win.height() $("html, body").animate({ scrollTop: scrollTarget }, 600); }); }); 
 .scroll { position: fixed; top: 0; left: 0; z-index: 10; } #content { height: 1000px; position: relative; } #content div { position: absolute; } #content .top { top: 20px; } #content .middle { top: 500px; } #content .bottom { bottom: 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="scroll"> <a href="#" id="scroll_id">click me</a> </div> <div id="content"> <div class="top">top</div> <div class="middle">middle</div> <div class="bottom">bottom</div> </div> 

Syntax Error: 语法错误:

<a onclick="scroll_down()" href="#" id="'scroll_id"> 

it should be 它应该是

     id="scroll_id"> 

(removed extra ') (已删除多余的')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM