gpt4 book ai didi

javascript - 随处使用函数,无需多次编写

转载 作者:行者123 更新时间:2023-11-28 15:33:21 25 4
gpt4 key购买 nike

试图让我的代码更干净,我不想多次编写相同的代码,但不知道如何完成它。您可以在下面的代码中看到,if/else 写了两次,但执行的操作相同。如何返回数据并再次调用该函数,并且只编写一次?

非常感谢帮助和建议。

代码是这样的:

(function($){
var scroll = $(this).scrollTop();
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
var headerBigWrapHeight = headerBigWrap.height();

var showNav = function() {
header.css('position','fixed');
headerBigWrap.css('display','none');
headerSmall.css('display','block');
}

var hideNav = function() {
header.css('position','static');
headerSmall.css('display','none');
headerBigWrap.css('display','block');
}

// don't want to write this more than once
// but need to call here on document ready
if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}


$(window).scroll(function(event){

scroll = $(this).scrollTop();

// here I need it again
// scroll is changing on scroll
// but "function" does exactly the same like above

if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}
});

})(jQuery);

如果您需要 html 和 css 工作示例:fiddle http://jsfiddle.net/cejs3jhs/和其余代码:

<header>
<div class="big">
<h1>Page Title</h1>
</div>
<div class="small">
<span class="icon nav-icon">Nav Icon</span>
</div>
</header>
<div class="page"></div>

<style type="text/css">
header {
width:100%;
background-color:red;
opacity:0.5;
}
header.toggle-nav {
height:100%;
}
header.toggle-nav ul {
display:block;
}
header > div {
position:relative;
width:976px;
margin:0 auto;
}
header > div.big {
padding:30px 0;
}
.page {
height:5000px;
background-color:orange;
opacity:0.5;
}
</style>

最佳答案

所以只需为此创建单独的函数:

function showHideNav(scroll, headerBigWrapHeight, element) {
var scroll = element.scrollTop(),
header = $('header'),
headerSmall = header.children('.small'),
headerBigWrap = header.children('.big')
headerBigWrapHeight = headerBigWrap.height();

if( scroll >= headerBigWrapHeight ) {
header.css('position','fixed');
} else {
header.css('position','static');
}

headerBigWrap.toggle();
headerSmall.toggle();
}

(function($){
showHideNav(scroll);

$(window).scroll(function(event){
scroll = $(this).scrollTop();
showHideNav(scroll);
});

})(jQuery);

关于javascript - 随处使用函数,无需多次编写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26334971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com