【问题标题】:jQuery 'if' statement not being recognisedjQuery 'if' 语句未被识别
【发布时间】:2016-05-02 02:31:15
【问题描述】:

我无法让我的 jQuery 识别 if 语句。请参阅 CodePen

我的网站中有 4 个页面转换。向右翻页、向左翻页、向上翻页和向下翻页。联系页面位于主要英雄部分下方的视线之外。上下转换将接触部分上下滑动到视图中。问题是如果用户打开联系页面并单击页面右侧或左侧,我希望联系页面滑回视线之外。我添加了一个 if 语句来查询联系人 div 的 marginTop 值,但它没有响应。

可以在上面的 CodePen 链接中查看以下内容。

$(document).ready(function() {

  // if statement that is not working but not sure why???

  if ($('.contact-wrapper').css("marginTop") == '-10%') {
    $('#down').trigger('click');

  }
  // --------------------------------------------

  $('#pg-right').click(function() {
    $('.home-wrapper, .about-wrapper').animate({
      marginLeft: '-=100%'
    }, 500);
  });

  $('#pg-left').click(function() {
    $('.home-wrapper, .about-wrapper').animate({
      marginLeft: '+=100%'
    }, 500);
  });

  $('#up').click(function() {
    $('.contact-wrapper').animate({
      marginTop: '-=10%'
    }, 500);
  });

  $('#down').click(function() {
    $('.contact-wrapper').animate({
      marginTop: '+=10%'
    }, 500);
  });
})
    .home-wrapper {

      position: fixed;

      background: blue;

      height: 90vh;

      left: 0;

      width: 100%;

    }

    .about-wrapper {

      position: fixed;

      background: green;

      height: 90vh;

      width: 100%;

      left: 100%;

    }

    .contact-wrapper {

      position: fixed;

      background: black;

      height: 80vh;

      width: 100%;

      left: 0;

      top: 90%;

    }

    #pg-right,

    #pg-left,

    #up,

    #down {

      position: fixed;

      font-size: 3em;

      color: white;

    }

    #pg-right {

      top: 10%;

      left: 80%;

    }

    #pg-left {

      top: 10%;

      left: 20%;

    }

    #up {

      top: 50%;

      left: 60%;

    }

    #down {

      top: 50%;

      left: 40%;

    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="home-wrapper"></div>

<div class="about-wrapper"></div>

<div class="contact-wrapper"></div>
<a href="#" id="pg-right">Right</a>
<a href="#" id="pg-left">Left</a>
<a href="#" id="up">Up</a>
<a href="#" id="down">Down</a>

【问题讨论】:

  • 尝试记录$('.contact-wrapper').css("marginTop"),看看结果如何。
  • @Xufox 好主意。它输出“0px”而不是“0%”。所以我想我可以通过使用“px”来解决这个问题,但出于响应原因,它并不理想。我想你不知道它评估 '%' 的方法吗?
  • 总是当您加载页面时,您将拥有相同的值 (0px) 并且如果从未有人参与过。我猜你想在点击处理程序上处理它,不是吗?

标签: jquery html css transition


【解决方案1】:

感谢@Xufox 为我指明了正确的方向。问题是 jQuery if 语句以像素为单位进行计算,而我使用的是 %.我解决此问题的方法是将字符串转换为整数值,然后查询它是否小于零。请参阅下面的代码以及更新后的CodePen

var x = $('.contact-wrapper').css("marginTop")

if( parseInt(x) < 0) {
  $('#down').trigger('click');
}

【讨论】:

    猜你喜欢
    • 2020-02-08
    • 2017-09-05
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多