此代码有什么问题?
function FloatMenu() {
var scrollAmount = $(document).scrollTop();
var newPosition = menuPosition + scrollAmount;
if ($(window).height() < $fl_menu.height() + $fl_menu_menu.height()) {
$fl_menu.css("top", menuPosition);
} else {
$fl_menu.stop().animate({
top: newPosition
}, $float_speed, $float_easing);
}
}
完整代码:
/* Floating Menu */
//config
$float_speed=500; //milliseconds
$float_easing="easeOutQuint";
$menu_fade_speed=500; //milliseconds
$closed_menu_opacity=0.75;
//cache vars
$fl_menu=$("#fl_menu");
$fl_menu_menu=$("#fl_menu .menu");
$fl_menu_label=$("#fl_menu .label");
$(window).load(function() {
menuPosition=$('#fl_menu').position().top;
FloatMenu();
$fl_menu.hover(
function(){ //mouse over
$fl_menu_label.fadeTo($menu_fade_speed, 1);
$fl_menu_menu.fadeIn($menu_fade_speed);
},
function(){ //mouse out
$fl_menu_label.fadeTo($menu_fade_speed, $closed_menu_opacity);
$fl_menu_menu.fadeOut($menu_fade_speed);
}
);
});
$(window).scroll(function () {
FloatMenu();
});
function FloatMenu(){
var scrollAmount=$(document).scrollTop();
var newPosition=menuPosition+scrollAmount;
if($(window).height()<$fl_menu.height()+$fl_menu_menu.height()){
$fl_menu.css("top",menuPosition);
} else {
$fl_menu.stop().animate({top: newPosition}, $float_speed, $float_easing);
}
}
错误是:
Message: 'menuPosition' is undefined
和
Message:'position().top' is null or not an object
答案 0 :(得分:0)
尝试在函数范围之外声明menuPosition
:
var menuPosition = 0; // declared outside of function scopes
/* Floating Menu */
//config
$float_speed=500; //milliseconds
$float_easing="easeOutQuint";
$menu_fade_speed=500; //milliseconds
$closed_menu_opacity=0.75;
//cache vars
$fl_menu=$("#fl_menu");
$fl_menu_menu=$("#fl_menu .menu");
$fl_menu_label=$("#fl_menu .label");
$(window).load(function() {
menuPosition=$('#fl_menu').position().top;
FloatMenu();
$fl_menu.hover(
function(){ //mouse over
$fl_menu_label.fadeTo($menu_fade_speed, 1);
$fl_menu_menu.fadeIn($menu_fade_speed);
},
function(){ //mouse out
$fl_menu_label.fadeTo($menu_fade_speed, $closed_menu_opacity);
$fl_menu_menu.fadeOut($menu_fade_speed);
}
);
});
$(window).scroll(function () {
FloatMenu();
});
function FloatMenu(){
var scrollAmount=$(document).scrollTop();
var newPosition=menuPosition+scrollAmount;
if($(window).height()<$fl_menu.height()+$fl_menu_menu.height()){
$fl_menu.css("top",menuPosition);
} else {
$fl_menu.stop().animate({top: newPosition}, $float_speed, $float_easing);
}
}
答案 1 :(得分:0)
在函数中使用参数。它会优雅地解决您的问题。
function FloatMenu(menuPosition) {
// Write your code as usual
}
// I guess you meant $(document).ready instead of $(window).load ?
// The main difference is that $(window).load will wait for all the images to be fully loaded, for example
$(document).ready(function() {
menuPosition=$('#fl_menu').position().top;
// Since you're using an argument, pass it!
FloatMenu(menuPosition);
// Or you can reduce to:
FloatMenu($('#fl_menu').position().top)