jQuery .offset()在所有浏览器中都不能正常工作

jQuery .offset() doesn't work properly at all in every browser

本文关键字:都不能 常工作 工作 offset jQuery 浏览器      更新时间:2023-09-26

我定义了这些变量:

var about = 0;
var music = $('.music-main').offset();
var programming = $('.programming-main').offset();
var contact = $('.contact-main').offset();

,然后尝试动画滚动到我的页面上的特定部分的按钮点击。

 case 0: $("html, body").animate({ scrollTop: 0}); break;
 case 1: $("html, body").animate({ scrollTop: music.top}); break;
 case 2: $("html, body").animate({ scrollTop: programming.top}); break;
 case 3: $("html, body").animate({ scrollTop: contact.top}); break;

但是它会滚动到不同的位置。它甚至会滚动到每个元素的不同位置。

请确保仅在页面加载后调用偏移量,否则坐标将不正确。

所以像这样做:

$( window ).load(function() {
  var about = 0;
  var music = $('.music-main').offset();
  var programming = $('.programming-main').offset();
  var contact = $('.contact-main').offset();
}

最好在点击的瞬间计算偏移量,这样在加载和点击之间页面大小的变化就不会有任何影响:

var about = 0;
var music = $('.music-main');
var programming = $('.programming-main');
var contact = $('.contact-main');
case 0: $("html, body").animate({ scrollTop: 0}); break;
case 1: $("html, body").animate({ scrollTop: music.offset().top}); break;
case 2: $("html, body").animate({ scrollTop: programming.offset().top}); break;
case 3: $("html, body").animate({ scrollTop: contact.offset().top}); break;