【问题标题】:how to move elements around web page using jQuery?如何使用 jQuery 在网页中移动元素?
【发布时间】:2022-01-22 17:19:54
【问题描述】:

我在我的网页上创建了三个形状(圆圈),它们使用 CSS 中的 z-index 定位在页面上其他元素的背景中,并且位置是绝对的。

我正试图在我的页面加载后立即在我的页面上移动它们。

以下是我编写的尝试执行上述操作的代码。我不确定我做错了什么。我们将不胜感激。

$(function() {
  $("shape-1").animate({
    "margin-top": "+= 200px"
  }, 2000);
  $("shape-2").animate({
    "margin-right": "+= 200px"
  }, 2000);
  $("shape-3").animate({
    "margin-bottom": "+= 200px"
  }, 2000);
});
.shape-1,
.shape-2,
.shape-3 {
  position: absolute;
  border-radius: 50%;
  background: linear-gradient(to right bottom, rgba(197, 96, 223, 0.904), rgba(255, 255, 255, 0.37));
  z-index: 1;
}

.shape-1 {
  top: 1%;
  left: 13%;
  height: 3rem;
  width: 3rem;
}
.shape-2 {
  top: 21%;
  right: 17%;
  height: 6rem;
  width: 6rem;
}
.shape-3 {
  width: 10rem;
  height: 10rem;
  bottom: 25%;
  left: 40%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shape-1"></div>
<div class="shape-2"></div>
<div class="shape-3"></div>

【问题讨论】:

  • 错字。选择器缺少类前缀,例如。 $('shape-1') 需要是$('.shape-1'),并且值需要没有空格才能被识别为增量操作:"+=200px"jsfiddle.net/RoryMcCrossan/mqjexapd

标签: javascript jquery css


【解决方案1】:
  • 您需要使用适当的 CSS 选择器选择元素。 $("shape-1") 不选择任何内容。 $(".shape-1") 会。
  • 您需要为确定元素位置的属性设置动画。动画margin-bottom 不会为您做任何事情。这些元素由topbottomleftright 固定到位。您需要为它们制作动画。
  • 您需要决定是使用百分比(如您的 CSS 定义)还是像素(如您的 JS 代码尝试)来定位元素。你不能将两者结合起来。
  • 您需要将百分比动画化为绝对值,您不能这样做+= 50%。您可以将元素从其原始绝对位置(例如1%)动画到新的绝对位置(例如50%)。

$(function() {
  $(".shape-1").animate({top: "50%", left: "50%"}, 2000);
  $(".shape-2").animate({right: "50%"}, 2000);
  $(".shape-3").animate({bottom: "10%"}, 2000);
});
.shape-1,
.shape-2,
.shape-3 {
  position: absolute;
  border-radius: 50%;
  background: linear-gradient(to right bottom, rgba(197, 96, 223, 0.904), rgba(255, 255, 255, 0.37));
  z-index: 1;
}
.shape-1 {
  top: 1%;
  left: 13%;
  height: 3rem;
  width: 3rem;
}
.shape-2 {
  top: 21%;
  right: 17%;
  height: 6rem;
  width: 6rem;
}
.shape-3 {
  width: 10rem;
  height: 10rem;
  bottom: 25%;
  left: 40%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shape-1"></div>
<div class="shape-2"></div>
<div class="shape-3"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2020-06-19
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    相关资源
    最近更新 更多