| | 73 | === <script> タグ === |
| | 74 | |
| | 75 | HTML 要素の属性値として !JavaScript を記述することができるのは分かりましたが、これだけだと、より長くて複雑なプログラムを記述したい場合には不便です。 |
| | 76 | |
| | 77 | そこで、属性値の中ではなく、もうちょっと別の場所に、プログラムをまとめて記述する方法を以下に示します。以下のサンプルプログラムは、「hoge」ボタンを押すたびに、ブラウザ画面上の至る所に「hoge」という文字を表示する、というものです。 |
| | 78 | |
| | 79 | {{{ |
| | 80 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> |
| | 81 | <html> |
| | 82 | |
| | 83 | <head> |
| | 84 | <meta http-equiv="content-type" content="text/html; charset=Shift_JIS"> |
| | 85 | <title>hoge</title> |
| | 86 | <script type="text/javascript" language="JavaScript"><!-- |
| | 87 | function putHoge() { |
| | 88 | var span = document.createElement("span"); |
| | 89 | with (span.style) { |
| | 90 | position = "absolute"; |
| | 91 | left = (Math.floor(Math.random() * |
| | 92 | (window.innerWidth ? window.innerWidth : document.documentElement.clientWidth))) + "px"; |
| | 93 | top = (Math.floor(Math.random() * |
| | 94 | (window.innerHeight ? window.innerHeight : document.documentElement.clientHeight))) + "px"; |
| | 95 | } |
| | 96 | span.appendChild(document.createTextNode("hoge")); |
| | 97 | document.getElementById("hoge_place").appendChild(span); |
| | 98 | }; |
| | 99 | //--></script> |
| | 100 | </head> |
| | 101 | |
| | 102 | <body> |
| | 103 | |
| | 104 | <form> |
| | 105 | <input type="button" value="hoge" OnClick="putHoge();"> |
| | 106 | </form> |
| | 107 | |
| | 108 | <div style="position: absolute; left: 0; top: 0;" id="hoge_place"></div> |
| | 109 | |
| | 110 | </body> |
| | 111 | |
| | 112 | </html> |
| | 113 | }}} |