jQueryの練習
HTMLの挿入、クラス属性の追加、スタイルの変更
HTML&CSS
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>jQueryの練習</title>
<style>
p.style {
color: #F00;
font-size: 36px;
background-color: #333;
}
</style>
<script src="../js/jquery-2.2.4.min.js"></script>
<script>
$(function(){
$('button').on('click',function(){
$('p').prepend('<strong>要素内の先頭に挿入(prepend)</strong>');
$('p').append('<strong>要素内の最後に挿入(append)</strong>');
$('p').before('<p>要素の前に挿入(before)</p>');
$('h1').after('<p>大見出しの後に挿入(after)</p>');
$('p').addClass('style');
$('h1').css({'color':'#F00','font-size':'40px','background-color':'#333'});
});
});
</script>
</head>
<body>
<button>変更</button>
<h1>大見出し</h1>
<p>テキスト</p>
</body>
</html>
処理結果
正方形の表示・非表示・移動
HTML&CSS
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>jQueryの練習</title>
<style>
div {
width: 300px;
height: 300px;
background-color: green;
display: none;
margin-left: 0;
}
div.move {
transform: translate(300px, 0);
transition: 1s;
}
</style>
<script src="../js/jquery-2.2.4.min.js"></script>
<script>
$(function(){
$('button#on').on('click',function(){ //「表示」ボタンクリック
$('div:not(:animated)').show(500);
});
$('button#off').on('click',function(){ //「非表示」ボタンクリック
$('div:not(:animated)').hide('slow');
});
$('button#on-off').on('click',function(){ //「表示・非表示」ボタンクリック
$('div:not(:animated)').toggle('fast');
});
$('button#move').on('click',function(){ //「移動」ボタンクリック
$('div:not(:animated)').animate({
"margin-left":"300px"
});
});
$('button#move2').on('click',function(){ //「移動2」ボタンクリック
$('div').toggleClass('move');
});
});
</script>
</head>
<body>
<button id="on">表示</button>
<button id="off">非表示</button>
<button id="on-off">表示・非表示</button>
<button id="move">移動</button>
<button id="move2">移動2</button>
<div></div>
</body>
</html>
処理結果
初期状態でボタンを押す前の状態
表示ボタンを押してから移動ボタンを押した状態
表示ボタンを押してから移動2ボタンを押した状態