首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用jQuery在网页周围移动元素?

如何使用jQuery在网页周围移动元素?
EN

Stack Overflow用户
提问于 2021-12-21 09:03:03
回答 1查看 68关注 0票数 2

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

当我的页面加载时,我正试图将它们移动到我的页面上。

下面是我编写的试图执行上述操作的代码。我不知道我做错了什么。我们将非常感谢提供援助。

代码语言:javascript
复制
$(function() {
  $("shape-1").animate({
    "margin-top": "+= 200px"
  }, 2000);
  $("shape-2").animate({
    "margin-right": "+= 200px"
  }, 2000);
  $("shape-3").animate({
    "margin-bottom": "+= 200px"
  }, 2000);
});
代码语言:javascript
复制
.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%;
}
代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-21 09:20:25

  • 您需要使用适当的CSS选择器来选择元素。$("shape-1")不选择任何东西。$(".shape-1")需要.
  • ,您需要对决定元素位置的属性进行动画化。动画margin-bottom不会对你有任何帮助。这些元素由topbottomleftright固定在一起。您需要对这些元素进行动画化。
  • 您需要决定是使用百分比(正如您的CSS定义的那样)还是使用像素(就像您的JS代码尝试的那样)来定位元素。您不能将两者结合在一起。
  • 您需要将百分比动画为绝对值,您不能做+= 50%。您可以将元素从其原始的绝对位置(例如,50%).

)动画到新的绝对位置(例如,1%)。

代码语言:javascript
复制
$(function() {
  $(".shape-1").animate({top: "50%", left: "50%"}, 2000);
  $(".shape-2").animate({right: "50%"}, 2000);
  $(".shape-3").animate({bottom: "10%"}, 2000);
});
代码语言:javascript
复制
.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%;
}
代码语言:javascript
复制
<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>

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70432860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档