【问题标题】:If-statement inside addClass function returns wrong valueaddClass 函数中的 if 语句返回错误值
【发布时间】:2013-01-12 17:31:57
【问题描述】:

Fiddle。在这个小提琴中,有两个下拉菜单。第一个是“Categorieën”,第二个是“Contact”。分配给列表项的类确定悬停时的箭头是指向左侧还是指向右侧(哪个空间的左侧空间最多)。下面的代码应该解决这个问题。但是,正如您在小提琴中看到的那样,“联系人”下拉列表项指向错误的方式,它应该指向左侧。

$("ul.sub-menu > li:not(':last-child')").addClass(function () {
  var $this = $(this),
    offL = $this.offset().left,
    wW = $(window).width();

  if (offL > ((wW / 2) - $this.width())) {
    return "over-left";
  } else {
    return "over-right";
  }
});

我哪里做错了?

【问题讨论】:

    标签: jquery if-statement addclass


    【解决方案1】:

    由于不显示菜单行,$this.width() 始终等于 0,并且您的条件永远不会满足。

    我在类属性循环之前添加了show(),以检索函数中使用的正确菜单宽度值。

    http://jsfiddle.net/tKL8E/33/

    // RELEVANT CDOE
    $("ul.sub-menu > li:not(':last-child')").show().addClass(function () {
      var $this = $(this),
        offL = $this.offset().left,
        wW = $(window).width();
      console.log(offL + ' ' + (wW/2) + ' ' + $this.width())
    
      if (offL >= ((wW / 2) - $this.width() - 238.5)) {
        return "over-left";
      } else {
        return "over-right";
      }
    });
    // /END RELEVANT CODE
    

    【讨论】:

    • show 不存在时,控制台会记录完全相同的值,所以我认为这不能解决问题。
    【解决方案2】:

    解决方案

    // We need to briefly show the sub-menu to get its offset and width
    $("ul.sub-menu").css({
      visibility: "hidden",
      display: 'block'});
    
      $("ul.sub-menu > li:not(':last-child')").each(function () {
        var $this = $(this);
        $this.addClass(function () {
          var offL = $this.offset().left,
            wW = $(window).width();
          if (offL > ((wW / 2) - $this.width())) {
            return "over-left";
          } else {
            return "over-right";
          }
        });
      });
    
    $("ul.sub-menu").css({
      visibility: "visible",
      display: "none"
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多