3

我正在尝试制作一个小动画,但我未能使其响应,因为“calc()”似乎不适用于 .animate。这里有另一种解决方案吗?

if (time == 1) {
  $("#message").animate({ marginTop: "calc(-15px + .8vw)" });
} else {
  $("#message").animate({ marginTop: "calc(0px + .8vw)" });
}

谨此致以最诚挚的问候, 贝尔纳多

编辑:我正在尝试为出现在我的网站 onchange() 下拉菜单上的消息设置动画。它应该是响应式的,所以这就是我使用 calc() 的原因。

<a>Time: </a><select id="time" onchange="setTime()" name="time" required>
                    <option value="1" selected>-</option>
                    <option value="3">-</option>
              </select></br>

那么有没有一种替代方法可以让它在没有 calc() 的情况下以另一种方式响应?

4

2 回答 2

5

由于vw是一个度量单位,等于视口宽度的 1%,我们可以将calc()语句计算为 jQuery 可以理解的值。

var time = true

$('#toggle').click(function () {
  time = !time;
  
  if (time === true) {
    // calc(-15px + .8vw)
    var calc = -15 + (0.08 * $(window).width()) + "px";
    $("#message").animate({ marginTop: calc });
  } else {
    // calc(0px + .8vw)
    var calc = 0 + (0.08 * $(window).width()) + "px";
    $("#message").animate({ marginTop: calc });
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">Toggle</button>
<div id="message">Message</div>

于 2017-07-20T10:40:14.063 回答
2

这是calc().

基本上我用这条线计算我的大众单位值:

var vw_value = $(window).width() / 100 * 0.8;

在这里工作小提琴。只需将time变量更改为 0 即可查看差异:

var time = 0;

var vw_value = $(window).width() / 100 * 0.8;

if (time == 1) {
  $("#one").animate({ marginTop: vw_value - 15 + "px" });
} else {
  $("#one").animate({ marginTop: vw_value + "px" });
}
body{
    margin:0;
    padding:0;
}
#one{
    margin-top:0;
    width: 40px;
    background:grey;
    height:40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one"></div>

于 2017-07-20T10:39:15.853 回答