Javascript 改变窗口大小

标签 javascript jquery html resize scroll

我试图在窗口大小调整时更改我的 JavaScript,但似乎无法让它工作。我想要的唯一区别是,当窗口变得小于 768px 时,offset().top 从 -90 更改为 -60。

这是我到目前为止所拥有的:

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top-90
        }, 1000);
        return false;
      }
    }
  });
});

$(window).resize(function(){
    if ($(window).width() <= 768){  
        $(function() {
          $('a[href*=#]:not([href=#])').click(function() {
            if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var target = $(this.hash);
              target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              if (target.length) {
                $('html,body').animate({
                  scrollTop: target.offset().top-60
                }, 1000);
                return false;
              }
            }
          });
        });
    }   
});

任何建议都会非常好!

谢谢

最佳答案

第一个点击事件处理程序 $('a[href*=#]:not([href=#])').click 每次运行 js 时都会绑定(bind)。

调整大小时,您将第二个处理程序附加到单击事件 - 它不会覆盖第一个处理程序 - 因此一个事件附加了两个事件处理程序。 我猜你想首先像 $('a[href*=#]:not([href=#])').off('click'); 一样取消绑定(bind)第一个事件处理程序调整窗口大小,然后附加第二个窗口。

但是由于您只更改一小段代码,您宁愿编写:

    $(function() {   $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top - ( ($(window).width() <= 768) ? 60 : 90)
            }, 1000);
            return false;
          }
        }   
        }); 
    });

注意scrollTop 行

关于Javascript 改变窗口大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501574/

相关文章:

javascript - 如何下载 MP4 文件而不是在浏览器上播放?

html - 删除文本下方输入字段中不需要的空格

javascript - 使用 CSS 或 Javascript 使圆形图像变暗

javascript - JSON 和多维数组上的 "Uncaught SyntaxError: Unexpected token o"

javascript - 在图像上创建具有用户输入大小的网格

javascript - initialDate 在 bootstrap-datetimepicker 中不起作用?

html - 现在 HTML5 有一个用于呈现页面的标准算法,它是否仍然对验证标记有用?

css - 推特 Bootstrap 中的表格宽度问题

javascript - javascript 无法从 jsp 获取数据

javascript - 无法让 parseInt 在 knockout.js 上工作(NaN 错误)