简体   繁体   English

动画滚动/使用jQuery显示隐藏元素

[英]Animated scroll / show hidden element using jQuery

There are several questions around similar to this and I have tried all suggestions, to no avail. 与此类似,有几个问题,我尝试了所有建议,但无济于事。

I have a text area and a button. 我有一个文本区域和一个按钮。 The button is initially hidden, but when the user types anything the button is shown. 该按钮最初是隐藏的,但是当用户键入任何内容时,都会显示该按钮。

In addition to this I want to scroll the page so that the button becomes visible. 除此之外,我还要滚动页面,以便按钮可见。 Example: 例:

$(document).ready(function () {

    $('#AddCommentEntryBox').on('keyup', function (e) {
        if ($(this).val() !== '') {
            $('#AddCommentButton').show();
            $(window).scrollTop($('#AddCommentButton').position().bottom);
            //$("html, body").animate({ scrollTop: $(document).height() }, 1000);
        } else {
            $('#AddCommentButton').hide();
        }
    });
});

http://jsfiddle.net/sJQcM/ http://jsfiddle.net/sJQcM/

EDIT: better example - I need to scroll a parent element, not the page: 编辑:更好的例子-我需要滚动一个父元素,而不是页面:

http://jsfiddle.net/sJQcM/3/ http://jsfiddle.net/sJQcM/3/

$(document).ready(function () {
    $('#AddCommentEntryBox').on('keyup', function (e) {
        if ($(this).val() !== '') {
            $('#AddCommentButton').show();
            $('html, body').stop().animate({scrollTop:$('#AddCommentButton').offset().top})
        } else {
            $('#AddCommentButton').hide();
        }
    });
});

FIDDLE 小提琴

You may want to exclude the backspace from this. 您可能要从中排除退格键。

Your example may have also worked, the reason it didn't is because .position() gives only .top or .left . 你举的例子可能也工作过,它没有的原因是因为.position()仅给出.top.left Bottom is not given (you have to calculate it yourself). 没有给出底部(您必须自己计算)。

You can also use .animate() with scrollTop for smooth scrolling. 您还可以将.animate()scrollTop一起使用,以实现平滑滚动。 In addition I recommend you wait for the user to stop typing for a few seconds before scrolling, otherwise it will scroll down and the textarea will be only partially visible. 另外,我建议您在滚动之前等待用户停止键入几秒钟,否则它将向下滚动并且textarea将仅部分可见。

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

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