jquery 获取变量(元素)的 .offset 值然后对其进行动画处理
jquery get .offset value of a variable(element) then animate to it
我有一个简单的导航。
<nav>
<a href="#section1">page 1</a>
<a href="#section2">page 2</a>
<a href="#section3">page 3</a>
</nav>
当用户单击其中一个链接时,我希望页面以动画方式显示到页面上的相应部分。
我似乎无法从变量中获取 .offset().top 值。任何帮助将不胜感激。
$("nav a").click(function(e) {
e.preventDefault();
// figure out which button was clicked
var targetName = $(this).attr("href");
// get the current position of the target element
var targetOffset = targetName.offset().top;
// send the page there
$("html, body").animate({
top: targetOffset
});
});
你需要设置适当的对象来制作动画,就像 Arun 说的那样,我错了 - 没有想清楚:)
$("nav a").click(function(e) {
e.preventDefault();
// figure out which button was clicked
var targetName = $(this).attr("href");
// get the current position of the target element
var targetOffset = $(targetName).offset().top;
// send the page there
$("html, body").animate({
scrollTop: targetOffset
}, 1400);
});
示例JSFIDDLE
问题是 targetName
不是 jQuery 对象,在您的控制台中您应该会看到类似 Uncaught TypeError: undefined is not a function
的错误
$("nav a").click(function(e) {
e.preventDefault();
// figure out which button was clicked
var targetName = $(this).attr("href");
// get the current position of the target element
var targetOffset = $(targetName).offset().top; //targetName is not jQuery object
// send the page there
$("html, body").animate({
scrollTop: targetOffset //also use scrollTop to animate scrolling
});
});
演示:Fiddle
我有一个简单的导航。
<nav>
<a href="#section1">page 1</a>
<a href="#section2">page 2</a>
<a href="#section3">page 3</a>
</nav>
当用户单击其中一个链接时,我希望页面以动画方式显示到页面上的相应部分。
我似乎无法从变量中获取 .offset().top 值。任何帮助将不胜感激。
$("nav a").click(function(e) {
e.preventDefault();
// figure out which button was clicked
var targetName = $(this).attr("href");
// get the current position of the target element
var targetOffset = targetName.offset().top;
// send the page there
$("html, body").animate({
top: targetOffset
});
});
你需要设置适当的对象来制作动画,就像 Arun 说的那样,我错了 - 没有想清楚:)
$("nav a").click(function(e) {
e.preventDefault();
// figure out which button was clicked
var targetName = $(this).attr("href");
// get the current position of the target element
var targetOffset = $(targetName).offset().top;
// send the page there
$("html, body").animate({
scrollTop: targetOffset
}, 1400);
});
示例JSFIDDLE
问题是 targetName
不是 jQuery 对象,在您的控制台中您应该会看到类似 Uncaught TypeError: undefined is not a function
$("nav a").click(function(e) {
e.preventDefault();
// figure out which button was clicked
var targetName = $(this).attr("href");
// get the current position of the target element
var targetOffset = $(targetName).offset().top; //targetName is not jQuery object
// send the page there
$("html, body").animate({
scrollTop: targetOffset //also use scrollTop to animate scrolling
});
});
演示:Fiddle