Javascript 在jQuery中合并3个函数
这些功能工作得非常完美,但我相信还有比这更聪明的方法:Javascript 在jQuery中合并3个函数,javascript,jquery,function,merge,Javascript,Jquery,Function,Merge,这些功能工作得非常完美,但我相信还有比这更聪明的方法: $(window).scroll(function(){ $('#header').css({ 'left': $(this).scrollLeft() + (($(window).width() - $("#header").width()) / 2) }); }); $(window).resize(function(){ $('#header').css({ 'left': $(this).scrollL
$(window).scroll(function(){
$('#header').css({
'left': $(this).scrollLeft() + (($(window).width() - $("#header").width()) / 2)
});
});
$(window).resize(function(){
$('#header').css({
'left': $(this).scrollLeft() + (($(window).width() - $("#header").width()) / 2)
});
});
$(function(){
$('#header').css({
'left': $(this).scrollLeft() + (($(window).width() - $("#header").width()) / 2)
});
});
将其封装在函数中,并在3个位置调用它
$(window).scroll(function () {
alignHeader()
});
$(window).resize(function () {
alignHeader()
});
$(function () {
alignHeader();
});
function alignHeader() {
$('#header').css({
'left': $(this).scrollLeft() + (($(window).width() - $("#header").width()) / 2)
});
}
您也可以尝试这种方法
$(window).on('resize scroll', alignHeader)
$(function () {
alignHeader();
});
function alignHeader() {
$('#header').css({
'left': $(this).scrollLeft() + (($(window).width() - $("#header").width()) / 2)
});
}
您可以为函数指定名称:
$(window).on('scroll resize', something).trigger('resize');
function something(){
$('#header').css({
'left': $(this).scrollLeft() + (($(window).width() - $("#header").width()) / 2)
});
}
我不明白在哪里调用了
$(function(){})
..@Ian我确实忘了将所有这些都打包到一个DOM就绪处理程序中,但是既然OP接受了这个答案,我想代码应该在页面的底部。他的DOM ready在原始代码中可能只是在加载时触发事件.trigger()
做同样的事情。就像一个符咒。谢谢卡尔·安德烈!