滚动

时间:2015-09-07 12:11:31

标签: jquery

我在另一个div滚出视图后出现div,但是第一个div有一个隐藏div的关闭按钮。但是,当页面滚动时,第一个代码将触发并再次重新打开div。

var element = $("#request-consultation").offset().top + $("#request-consultation").outerHeight();
$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= element) {
    $("#request-consultation-float").show('slow');
  } else {
    $("#request-consultation-float").hide('slow');
  }
});

$(".request-float-close span").click(function() {       
    $('#request-consultation-float').hide('slow');
});

如何在点击#request-consultation-float后隐藏.request-float-close div?

3 个答案:

答案 0 :(得分:0)

你可以使用一个标志变量来检查它是否被点击:

var isClicked = false;
var element = $("#request-consultation").offset().top + $("#request-consultation").outerHeight();
$(window).scroll(function() {
    if(isClicked) return;
  var scroll = $(window).scrollTop();
  if (scroll >= element) {
    $("#request-consultation-float").show('slow');
  } else {
    $("#request-consultation-float").hide('slow');
  }
});

$(".request-float-close span").click(function() {       
    $('#request-consultation-float').hide('slow');
    isClicked = true;
});

答案 1 :(得分:0)

您可以记住点击并按照以下方式行事:

var element = $("#request-consultation").offset().top + $("#request-consultation").outerHeight();
var closeClicked = false;
$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= element && !closeClicked) {
    $("#request-consultation-float").show('slow');
  } else {
    $("#request-consultation-float").hide('slow');
  }
});

$(".request-float-close span").click(function() {       
    $('#request-consultation-float').hide('slow');
    closeClicked = true;
});

答案 2 :(得分:0)

Remove the specific event handler

var element = $("#request-consultation").offset().top + $("#request-consultation").outerHeight();

function myCustomScroll() {
    var scroll = $(window).scrollTop();
    if (scroll >= element) {
        $("#request-consultation-float").show('slow');
    } else {
        $("#request-consultation-float").hide('slow');
    }
}

$(window).scroll(myCustomScroll);

$(".request-float-close span").click(function() {       
    $('#request-consultation-float').hide('slow');
    $(window).unbind('scroll', myCustomScroll);
});

如果您不想保留对侦听器功能的引用,可以使用namespacing

var element = $("#request-consultation").offset().top + $("#request-consultation").outerHeight();

$(window).on('scroll.consultationFloat', function() {
    var scroll = $(window).scrollTop();
    if (scroll >= element) {
        $("#request-consultation-float").show('slow');
    } else {
        $("#request-consultation-float").hide('slow');
    }
});

$(".request-float-close span").click(function() {       
    $('#request-consultation-float').hide('slow');
    $(window).unbind('scroll.consultationFloat');
});