我正在練習 jquery 并嘗試通過按下影片按鈕(一次)來為各個方向的 div 設定影片。該代碼適用于將 div 向右和底部移動,但不適用于將 div 向左和向上移動。
這是我到目前為止寫的代碼
$(document).ready(function() {
$("button").click(function() {
for (var i = 0; i < 4; i ) {
if (i == 0) {
$("div").animate({
left: '250px'
});
}
if (i == 1) {
$("div").animate({
top: '250px'
});
}
if (i == 2) {
$("div").animate({
left: '-250px'
});
}
if (i == 3) {
$("div").animate({
top: '-250px'
});
}
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Lab 8</title>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">I am a box</div>
</body>
</html>
uj5u.com熱心網友回復:
left當您為和設定負值時top,它們會將框移出視口,因為它絕對定位于身體。將它們設定為0px第 3 次和第 3 次互動。
您可以添加一個父position: relative;級以更好地觀察影片(以全頁模式查看):
$(document).ready(function() {
$("button").click(function() {
for (var i = 0; i < 4; i ) {
if (i == 0) {
$("div").animate({
left: '250px'
});
}
if (i == 1) {
$("div").animate({
top: '250px'
});
}
if (i == 2) {
$("div").animate({
left: '0px' // Back to original position left
});
}
if (i == 3) {
$("div").animate({
top: '0px' // Back to original position top
});
}
}
});
});
.parent {
position: relative;
}
.box {
position: absolute;
background: #98bf21;
height: 100px;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div class="parent">
<div class="box">I am a box</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/463842.html
標籤:javascript html
