午前の続き
#ball{
width: 20px;
height: 20px;
background: #fff;
border-radius: 10px;/*丸くする*/
position: absolute;/*絶対配置 これを定義するとtopとかleftが使えるようになる*/
/*場合によっては親要素さえはみでる*/
top: 10px;
left: 10px;
}
→親要素stageをはみでてしまう。
これを回避するには親要素にもpositionを指定する必要がある。
→#stage{}に追加
position: relative;/*レイアウトに影響なし*/
つまり親要素にpositionがかかっていて初めて、
子要素の絶対配置(親要素にたいして)がかかるようになる
先生がいつもbotton要素をpで包むのは
ボックスの中に配置したいから。
アニメーションをどう作るか?
①最後の形を指定しておしまい
②もっと細かく何ミリ秒でそれをするとか指定する
③そのほか
ボタンを押したときにballが移動
$(function(){
$('#btn').on('click',function(){
console.log('hoge');
$('#ball').css('left','10px');
$('#ball').animate({'left':'780px'},1500);
});
});
animateメソッドのパラメーターは「オブジェクト」です。
よって{}で囲う必要がある。
できあがりの『オブジェクト』を指定している。
ballが往復(自分でやった分)/functionで記述
$(function(){
$('#btn').on('click',function(){
console.log('hoge');
$('#ball').animate({'left':'10px'},1500,function(){
$('#ball').animate({'left':'780px'},1500);
});
});
});
ballが往復/参考としてメソッドチェーンで記述
$('#btn2').on('click',function(){
$('#ball').animate({'left':'10px'},1500).animate({'left':'780px'},1500);
});
test2を作ってもう一度自分で作ってみましょう
--->test2.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>絶対配置</title>
<link rel="stylesheet" href="test2.css">
<script src="../jquery-3.4.1.min.js"></script>
</head>
<body>
<h1>絶対配置と<span class="green">相対配置</span></h1>
<p><button id="btn">start</button></p>
<div id="stage">
<div id="ball"></div>
</div>
<script src="test2.js"></script>
</body>
</html>
--->test2.css
body{
background: #cff;
}
#stage{
width: 800px;
height: 400px;
background: #000;
position: relative;
}
#ball{
background: #fff;
width: 20px;
height: 20px;
position: absolute;
border-radius: 10px;
top: 200px;
left: 0px;
}
--->test2.js
$(function(){
$('#btn').on('click',function(){
$('#ball').animate({'left':'780px'},1500,function(){
$('#ball').animate({'left':'0px'},1500);
});
})
});