Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery.offset()在所有浏览器中都不能正常工作_Javascript_Jquery - Fatal编程技术网

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

Javascript jQuery.offset()在所有浏览器中都不能正常工作,javascript,jquery,Javascript,Jquery,我定义了这些变量: 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

我定义了这些变量:

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;

你想为这个制作一把小提琴,这样我们就可以看到它的作用了吗?