窗口高度在浏览器调整大小时不起作用

时间:2018-02-19 16:08:08

标签: javascript jquery

当页面有滚动条时,或者换句话说当浏览器高度超过用户桌面分辨率时,我有这段代码显示“滚动到底部”链接。无论如何,如果浏览器窗口高度在页面最初加载时更大,但是如果我在页面加载后调整窗口大小,则它不会正常工作,那么它就不会触发。

任何帮助都将不胜感激。

$(function() {
    // Check to see if window has scrollbars
        if ($(document).height() > $(window).height()) {
            $('.scrollToBottom').animate({
                opacity : 'show',
                height : 'show'
            }, 'fast');
        } else {
            $('.scrollToBottom').animate({
                opacity : 'hide',
                height : 'hide'
            }, 'fast');
        }
    // Click event to scroll to bottom
    $('.scrollToBottom').click(function() {
        $('html, body').animate({
            scrollTop : $(document).height()-$(window).height()
        }, 1500, 'easeOutQuint');
        return false;
    });
});

1 个答案:

答案 0 :(得分:1)

这是因为它没有“触发器”。

在文档准备就绪时,请参阅此语句$(function() { .// code }),执行代码。

您需要的是浏览器调整大小时的另一个触发器:

$(window).resize(function (){
  if ($(document).height() > $(window).height()) {
    $('.scrollToBottom').animate({
        opacity : 'show',
        height : 'show'
    }, 'fast');
  } else {
      $('.scrollToBottom').animate({
          opacity : 'hide',
          height : 'hide'
      }, 'fast');
  }
})

既然你不想重复自己,你应该写一个函数并在这些“触发器”中调用它。

function showBar() {
  if ($(document).height() > $(window).height()) {
    $('.scrollToBottom').animate({
        opacity : 'show',
        height : 'show'
    }, 'fast');
  } else {
      $('.scrollToBottom').animate({
          opacity : 'hide',
          height : 'hide'
      }, 'fast');
  }
}

$(window).resize(function (){
  showBar();
})

$(function() {
  showBar();
})

这些触发器称为事件。以供参考: https://developer.mozilla.org/en-US/docs/Web/Events

相关问题