javascript - 如何使用 jQuery 在网页上移动元素?

标签 javascript jquery css

我在网页上创建了三个形状(圆形),它们使用 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>

最佳答案

  • 您需要使用适当的 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>

关于javascript - 如何使用 jQuery 在网页上移动元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70432860/

相关文章:

html - 如何制作带有折叠 Angular 的 45 度响应色带?

android - Android 浏览器中的中心按钮

javascript - 使用js显示日期取决于它是否是该月的最后一天

c# - 使用 javascript 搜索按钮单击 Enter 按键

jquery 简单的 ajax 加载而不加载其包装器 DIV

jquery - 根据按钮的属性值添加/删除 css 类

css - 将 div 与同级 div 的底部对齐,而不知道同级 div 的高度

javascript - html 输入工作不正确

javascript - 为什么包含 "this"的方法不能作为数组方法传入另一个方法中

javascript - 如何在选择标签旁边添加按钮