jQuery动画到可变高度

时间:2013-04-03 20:00:39

标签: jquery variables

我想要一个折叠上方的按钮,上面写着“向下滚动!”点击后。我想让它为整个浏览器高度设置动画。由于人们有不同的屏幕分辨率。我想使用变量。然而,这是不可能的。

下面的代码有效,但只有设置高度为800px。

相反,我需要它来使用var hheight

我一直在寻找stackoverflow,只有很少的线索可以跟随,而且没有真正的解决方案。

这是有效的:

function jqUpdateSize(){
    // Get the dimensions of the viewport
    var width = jQuery(window).width();
    var hheight = jQuery(window).height();

    jQuery('#jqWidth').html(width);
    jQuery('#jqHeight').html(hheight);
};
jQuery(document).ready(jqUpdateSize);    // When the page first loads
jQuery(window).resize(jqUpdateSize);     // When the browser changes size

jQuery(document).ready(function() {
    jQuery(".my-btn").click(function(event){
    jQuery('html, body').animate({scrollTop:'+=' + 800 + 'px'}, '800');
    });
});

以下无效:

jQuery('html, body').animate({scrollTop:'+=' + hheight+ 'px'}, '800');

希望有人知道如何处理这个问题。

2 个答案:

答案 0 :(得分:0)

您需要ready()resize()

中的匿名函数

所以,

jQuery(document).ready(function(){jqUpdateSize();});
jQuery(window).resize(function(){jqUpdateSize();}); 

否则,您的jqUpdateSize函数永远不会被调用而您的变量hheight中没有任何内容

最佳做法是将所有内容放入document.ready()

像这样:

jQuery(document).ready(function() {
    jqUpdateSize();
    jQuery(window).resize(function(){jqUpdateSize();});
    jQuery(".my-btn").click(function(event){
        jQuery('html, body').animate({scrollTop:'+=' + hheight + 'px'}, '800');
    });
});

答案 1 :(得分:0)

var hheight = jQuery(window).height();
jQuery('html, body').animate({scrollTop:'+=' + hheight+ 'px'}, '800');

这项工作很好--- demo

尝试在jQuery(window).resize(jqUpdateSize);

中移动此ready

它看起来应该是这样的

jQuery(document).ready(function() {
    jQuery(window).resize(jqUpdateSize);
    jQuery(".my-btn").click(function(event){
    jQuery('html, body').animate({scrollTop:'+=' + 800 + 'px'}, '800');
    });
});