如何使用jQuery在网页中移动元素



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

页面加载后,我会尝试在页面中移动它们。

以下是我为完成上述操作而编写的代码。我不确定我做错了什么。我们将非常感谢您的协助。

$(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>

最新更新