我有两个JS片段,并希望实现这个逻辑:第二个JS正在运行,直到第一个激活为止(它在单击时激活,我也有当按此按钮时打开的菜单),然后当再次单击(菜单关闭)时,第二个JS片段必须被取消暂停(并且再次打开)。请建议我如何‘合并’他们在一起?
1)
<script type="text/javascript">
jQuery(function() {
jQuery('#menuicon-label').click(function(e) {
var clicks = jQuery(this).data('clicks');
if (clicks) {
jQuery('html').css({'position': '', 'left': '', 'right': '', 'top': '', 'bottom': '', 'overflow': ''});
} else {
jQuery('html').css({'position': 'fixed', 'left': '0', 'right': '0', 'top': '0', 'bottom': '0', 'overflow': 'hidden'});
}
jQuery(this).data("clicks", !clicks);
});
});
</script>
2)
<script type="text/javascript">
jQuery(function() {
jQuery(window).scroll(function(){
var top = jQuery(window).scrollTop();
if(top>48) { // height of float header
jQuery('#main').css("paddingTop", "96px");
jQuery('#cloakaglobal').css("display", "none");
} else {
jQuery('#main').css("paddingTop", "0px");
jQuery('#cloakaglobal').css("display", "");
}
});
});
</script>
发布于 2019-08-13 18:42:15
您应该在jQuery中使用取消绑定功能。在第一个片段中做下面的修改-
<script type="text/javascript">
jQuery(function() {
var trackTheSecondJs=true;
jQuery('#menuicon-label').click(function(e) {
if(trackTheSecondJs){
jQuery(window).unbind("scroll",scrollHandler);
trackTheSecondJs=false;
}else{
jQuery(window).bind("scroll",scrollHandler);
trackTheSecondJs=true;
}
var clicks = jQuery(this).data('clicks');
if (clicks) {
jQuery('html').css({'position': '', 'left': '', 'right': '', 'top': '', 'bottom': '', 'overflow': ''});
} else {
jQuery('html').css({'position': 'fixed', 'left': '0', 'right': '0', 'top': '0', 'bottom': '0', 'overflow': 'hidden'});
}
jQuery(this).data("clicks", !clicks);
});
});
</script>
现在,在第二个片段中,使用指向函数的指针,而不是将函数本身作为滚动函数的参数。因此,使用这个指针,可以像前面那样在第一个片段中完成取消绑定。
<script type="text/javascript">
function scrollHandler(){
var top = jQuery(window).scrollTop();
if(top>48) { // height of float header
jQuery('#main').css("paddingTop", "96px");
jQuery('#cloakaglobal').css("display", "none");
} else {
jQuery('#main').css("paddingTop", "0px");
jQuery('#cloakaglobal').css("display", "");
}
}
jQuery(function() {
jQuery(window).scroll(scrollHandler);
});
</script>
希望这能有所帮助。
https://stackoverflow.com/questions/57483372
复制相似问题