[英]Show div on scroll 200px but hide it on click
I have a div element #offer that is hidden by default and that is displayed on scrolling 200px from top, the div is being hidden once a user scrolls up again. 我有一个div元素#offer,默认情况下是隐藏的,并且在从顶部滚动200px时显示,一旦用户再次向上滚动,div就会被隐藏。
The following code does this just alright: 以下代码可以正常执行此操作:
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 100) {
$('#offer').fadeIn();
} else {
$('#offer').fadeOut();
}
});
I would like to add an option to hide the div manually simply by clicking on #hide-now div . 我想添加一个选项,只需单击#hide-now div即可手动隐藏div 。 I have tried to use the following piece of code.
我试图使用以下代码。 Even though this hides the div #offer, the div is being displayed immediately again (because the scroll distance from top is more than 200px).
即使这隐藏了div #offer,该div仍会立即再次显示(因为从顶部开始的滚动距离超过200像素)。 What tweak in a code do I need to do to get this working?
我需要对代码进行哪些调整才能使其正常工作?
$(document).ready(function() {
$("#hide-now").live('click', function () {
$("#offer").slideUp("slow");
});
});
Any ideas how to solve this? 任何想法如何解决这个问题? Thanks in advance for your help.
在此先感谢您的帮助。
I'd add a class to the div once it's been hidden, and then check if that class exists inside the scroll event handler. 一旦将其隐藏,我将向div添加一个类,然后检查滚动事件处理程序中是否存在该类。 Try this out:
试试看:
$(document).ready(function() {
$("#hide-now").live('click', function () {
$("#offer").slideUp("slow").addClass("manually_hidden");;
});
});
Then inside the scroll handler: 然后在滚动处理程序中:
$(document).scroll(function () {
var y = $(this).scrollTop();
if (!$("#offer").hasClass("manually_hidden")) {
if (y > 100) {
$('#offer').fadeIn();
} else {
$('#offer').fadeOut();
}
}
});
Hope this helps! 希望这可以帮助! Also, I agree w/ the other comment to avoid using .live - .on or just a .click ought to do it.
另外,我同意使用其他注释来避免使用.live-.on或仅使用.click应该这样做。
So create a Boolean (for example, show
) and check that Boolean before you perform the fadeIn
action for your scroll
handler. 因此,创建一个布尔值(例如
show
)并在执行scroll
处理程序的fadeIn
操作之前检查该布尔值。
So, 所以,
var show = true;
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 100) {
if(show){
$('#offer').fadeIn();
}
} else {
$('#offer').fadeOut();
}
});
Then, if they click
, 然后,如果他们
click
,
$(document).ready(function() {
$("#hide-now").live('click', function () {
$("#offer").slideUp("slow");
show = false;
});
});
As with the others, I recommend using on
instead of live
. 与其他应用程序一样,我建议使用
on
而不是live
。
Set a flag when #offer is manually hidden (say, with a class): 手动隐藏#offer(例如,带有类)时设置标志:
$(function() {
$("#hide-now").on('click', function () {
$("#offer").slideUp("slow").addClass('hidden');
});
});
Then check for the flag: 然后检查标志:
$(document).scroll(function () {
var y = $(this).scrollTop();
if ( ! $(this).hasClass('hidden') ) {
if (y > 100) {
$('#offer').fadeIn();
} else {
$('#offer').fadeOut();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.