2010年6月5日土曜日

2. サンプル コード1

<pre> <next>
まずは、以下のコードを見てください。このコードはファイルにしてSafariでローカルに実行できます。

実行すると灰色の四角が表示され、表示された灰色の四角をクリックするとクリックした位置のX座標と四角の左端の座標、そしてmyRectオブジェクトのメンバであるmyVarの"this is myVar"がアラートボックスに表示されます。
  1. <html>  
  2. <head>  
  3. <style>  
  4. .myCSS {  
  5.   background-color: rgb(240, 240, 240);  
  6.   height: 250px;  
  7.   width: 200px;  
  8.   position: absolute;  
  9.   left: 200px;  
  10.   top: 200px;  
  11. }  
  12. </style>  
  13. <script>  
  14. function MyObject() {  
  15.  var self = this;  
  16.  this.myVar = "this is myVar";  
  17.  var myObject = document.createElement('div');  
  18.  myObject.className = 'myCSS';  
  19.  myObject.addEventListener('mousedown'function(e) { self.myHandler(e) }, false);  
  20.  this.myObject = myObject;  
  21.  document.body.appendChild(myObject);  
  22. }  
  23.   
  24. MyObject.prototype.myHandler = function(e) {  
  25.  alert(e.clientX);  
  26.   alert(this.myObject.offsetLeft);  
  27.   alert(this.myVar);  
  28. }  
  29.   
  30. function loaded() {  
  31.  myRect = new MyObject;  
  32. }  
  33. </script>  
  34. </head>  
  35. <body onload="loaded()">  
  36. </body>  
  37. </html>  
<pre> <next>

0 件のコメント: