プレビュー機能作成
プレビュー機能とは(名前が正しいかわかりませんが)、Qiitaの投稿時の右側の画面のように、入力すると非同期で表示がされる機能のことです。
ブログ記事を書く際や、マークダウンでの記述の場合はよく使用されますよね!
今回は基礎ということで簡単なプレビューを作成致します。
HTML5
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title></head><style>#sampleForm,#sampleOutput{padding:150px;width:25vw;height:50vh;margin:10px;/* padding: 10px; */border:1pxsolidgray;border-radius:10px;display:inline-block;}#sampleForm{background-color:#f0f8ff;}#sampleOutput{background-color:#00ffff;}#sampleForm*{margin:0000;vertical-align:text-top;}</style><body><formid="sampleForm">【入力欄】
<br/>名前:<inputtype="text"name="formName"value=""><br/>地域:
<selectname="formArea"><optionselected>関東</option><option>東海</option><option>関西</option></select><br/>年齢:
<selectname="formAge"><optionselected>10代</option><option>20代</option><option>30代</option></select><br/>コメント:<textareaname="formComent"></textarea><br/></form><divid="sampleOutput">【出力欄】
<br/>名前:<spanid="sampleOutputName"></span><br/>地域:<spanid="sampleOutputArea"></span><br/>年齢:<spanid="sampleOutputAge"></span><br/>コメント:<spanid="sampleOutputComent"></span><br/></div><script src="js/script.js"></script></body></html>
// !非同期 フォームの内容の変更を特定の要素に即反映window.onload=function(){//load イベント発生時に呼び出す関数への参照または関数式getValue();//関数の中にValueを定義します。var$formObject=document.getElementById("sampleForm");//id要素の取得for(var$i=0;$i<$formObject.length;$i++){//上記のidの入った変数$formObjectの配列の長さ分for分で回します$formObject.elements[$i].onkeyup=function(){getValue();//配列で回したValueに対してKeyupされた時にgetValue関数を起動させます。};$formObject.elements[$i].onchange=function(){getValue();//配列で回したValueに対してKeyupされた時にgetValue関数を起動させます。};}document.getElementById("sampleOutputLength").innerHTML=$formObject.length;}functiongetValue(){//getValue関数を定義しますvar$formObject=document.getElementById("sampleForm");document.getElementById("sampleOutputName").innerHTML=$formObject.formName.value;document.getElementById("sampleOutputArea").innerHTML=$formObject.formArea.value;document.getElementById("sampleOutputAge").innerHTML=$formObject.formAge.value;document.getElementById("sampleOutputComent").innerHTML=$formObject.formComent.value;}
以上説明は簡単にコメントアウトで行なっております。
簡単な記述になるので是非コピペして変更をして楽しんでみては。