我在网页上创建了三个形状(圆形),它们使用 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
对你没有任何作用。这些元素通过top
、bottom
、left
和right
固定到位。您需要为它们设置动画。 - 您需要决定是使用百分比(如 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/