JavaScript DHTML/HTML/Layer

Материал из Web эксперт
Перейти к: навигация, поиск

Accessing Layers with JavaScript

   <source lang="html4strict">

/* JavaScript Unleashed, Third Edition by Richard Wagner and R. Allen Wyke ISBN: 067231763X Publisher Sams CopyRight 2000

  • /

<html> <head>

 <title>JavaScript Unleashed</title>
 <style type="text/css">
 
 </style>
 <script type="text/javascript" language="JavaScript1.2">
 
 </script>

</head> <body onload="checkBrowser()">

   DIV 1
 <form name="form1">
   <input type="button" value="Hide"Image from book 
          onclick="changeState("layer1","hidden")">
   <input type="button" value="Show"Image from book 
          onclick="changeState("layer1","visible")">
 <form>

</body> </html>

      </source>
   
  


Adjusting Layer clip Properties (W3C)

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Layer Clip</TITLE> <SCRIPT LANGUAGE="JavaScript"> var origLayerWidth = 0 var origLayerHeight = 0 var currTop, currRight, currBottom, currLeft function init() {

   origLayerWidth = parseInt(document.getElementById("display").style.width)
   origLayerHeight = parseInt(document.getElementById("display").style.height)
   currTop = 0
   currRight = origLayerWidth
   currBottom = origLayerHeight
   currLeft = 0
   showValues()

} function setClip(field) {

   var val = parseInt(field.value)
   switch (field.name) {
       case "top" :
           currTop = val

break

       case "right" :
           currRight = val
           break
       case "bottom" :
           currBottom = val
           break
       case "left" :
           currLeft = val
           break
       case "width" :
           currRight = currLeft + val
           break
       case "height" :
           currBottom = currTop + val
           break
   }
   adjustClip()
   showValues()

} function adjustClip() {

   document.getElementById("display").style.clip = "rect(" + currTop + "px " +
   currRight + "px " + currBottom + "px " + currLeft + "px)"

} function showValues() {

   var form = document.forms[0]
   form.top.value = currTop
   form.right.value = currRight
   form.bottom.value = currBottom
   form.left.value = currLeft
   form.width.value = currRight - currLeft
   form.height.value = currBottom - currTop

} var intervalID function revealClip() {

   var midWidth = Math.round(origLayerWidth /2)
   var midHeight = Math.round(origLayerHeight /2)
   currTop = midHeight
   currBottom = midHeight
   currRight = midWidth
   currLeft = midWidth
   intervalID = setInterval("stepClip()",1)

} function stepClip() {

   var widthDone = false
   var heightDone = false
   if (currLeft > 0) {
       currLeft += -2
       currRight += 2
   } else {
       widthDone = true
   }
   if (currTop > 0) {
       currTop += -1
       currBottom += 1
   } else {
       heightDone = true
   }
   adjustClip()
   showValues()
   if (widthDone && heightDone) {
       clearInterval(intervalID)
   }

} </SCRIPT> </HEAD> <BODY onLoad="init()">

Layer Clipping Properties (W3C)


Enter new clipping values to adjust the visible area of the layer.

<FORM>

layer.style.clip (left): <INPUT TYPE="text" NAME="left" SIZE=3 onChange="setClip(this)">
layer.style.clip (top): <INPUT TYPE="text" NAME="top" SIZE=3 onChange="setClip(this)">
layer.style.clip (right): <INPUT TYPE="text" NAME="right" SIZE=3 onChange="setClip(this)">
layer.style.clip (bottom): <INPUT TYPE="text" NAME="bottom" SIZE=3 onChange="setClip(this)">
layer.style.clip (width): <INPUT TYPE="text" NAME="width" SIZE=3 onChange="setClip(this)">
layer.style.clip (height): <INPUT TYPE="text" NAME="height" SIZE=3 onChange="setClip(this)">

<INPUT TYPE="button" VALUE="Reveal Original Layer" onClick="revealClip()"> </FORM>

ARTICLE I

<P> Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or

abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the
government for a redress of grievances.

</P>

</BODY> </HTML>

      </source>
   
  


Comparison of Layer and Clip Location Properties (W3C)

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Layer vs. Clip</TITLE> <SCRIPT LANGUAGE="JavaScript"> var currClipTop = 0 var currClipLeft = 0 var currClipRight = 360 var currClipBottom = 180 function setClip(field) {

   var val = parseInt(field.value)
   switch (field.name) {
       case "clipBottom" :
           currClipBottom = val
           break
       case "clipRight" :
           currClipRight = val
           break
   }
   adjustClip()
   showValues()

} function adjustClip() {

   document.getElementById("display").style.clip = "rect(" + currClipTop + 
   "px " + currClipRight + "px " + currClipBottom + "px " + currClipLeft + 
   "px)"

} function setLayer(field) {

   var val = parseInt(field.value)
   switch (field.name) {
       case "width" :
           document.getElementById("display").style.width = val + "px"
           break
       case "height" :
           document.getElementById("display").style.height = val + "px"
           break
   }
   showValues()

} function showValues() {

   var form = document.forms[0]
   var elem = document.getElementById("display")
   var clipRect = getClipRect(elem)
   form.width.value = parseInt(elem.style.width)
   form.height.value = parseInt(elem.style.height)
   form.clipRight.value = clipRect.right
   form.clipBottom.value = clipRect.bottom

} // convert clip property string to an object function getClipRect(elem) {

   var clipString = elem.style.clip
   // assumes "rect(npx, npx, npx, npx)" form
   // get rid of "rect("
   clipString = clipString.replace(/rect\(/,"")
   // get rid of "px)"
   clipString = clipString.replace(/px\)/,"")
   // get rid of remaining "px" strings
   clipString = clipString.replace(/px/g,",")
   // turn remaining string into an array
   clipArray = clipString.split(",")
   // make object out of array values

var clipRect = {top:parseInt(clipArray[0]), right:parseInt(clipArray[1]),

   bottom:parseInt(clipArray[2]), left:parseInt(clipArray[3])}
   return clipRect

} </SCRIPT> </HEAD> <BODY onLoad="showValues()">

Layer vs. Clip Dimension Properties (W3C)


Enter new layer and clipping values to adjust the layer.<P>

<FORM>

layer.style.width: <INPUT TYPE="text" NAME="width" SIZE=3 onChange="setLayer(this)">
layer.style.height: <INPUT TYPE="text" NAME="height" SIZE=3 onChange="setLayer(this)">
layer.style.clip (right): <INPUT TYPE="text" NAME="clipRight" SIZE=3 onChange="setClip(this)">
layer.style.clip (bottom): <INPUT TYPE="text" NAME="clipBottom" SIZE=3 onChange="setClip(this)">

</FORM>

ARTICLE I

<P> Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances. </P>

</BODY> </HTML>

      </source>
   
  


Detecting Navigator and Internet Explorer

   <source lang="html4strict">

/* JavaScript Unleashed, Third Edition by Richard Wagner and R. Allen Wyke ISBN: 067231763X Publisher Sams CopyRight 2000

  • /

<html> <body>

<script language="JavaScript">

</script>


This is a block of moving buttons <form> <input type="button"

      value="UP"
      onClick="moveUp()">

<input type="button"

      value="DOWN"
      onCLick="moveDown()">

<input type="button"

      value="LEFT"
      onClick="moveLeft()">

<input type="button"

      value="RIGHT"
      onClick="moveRight()">

<input type="button"

      value="SHOW/HIDE Text Box"
      onClick="showHide()">

</form>

<script language="JavaScript">

</script>

<script language="JavaScript">

</script>


<script language="JavaScript">

</script>

</body> </html>

      </source>
   
  


Dragging a Layer (W3C)

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Layer Dragging</TITLE> <STYLE TYPE="text/css"> .draggable {cursor:hand} </STYLE> <SCRIPT LANGUAGE="JavaScript"> var engaged = false var offsetX = 0 var offsetY = 0 function dragIt(evt) {

   evt = (evt) ? evt : (window.event) ? window.event : ""
   var targElem = (evt.target) ? evt.target : evt.srcElement
   if (engaged) {
       if (targElem.className == "draggable") {
           while (targElem.id != "myLayer" && targElem.parentNode) {
               targElem = targElem.parentNode
           }
           if (evt.pageX) {
               targElem.style.left = evt.pageX - offsetX + "px"
               targElem.style.top = evt.pageY - offsetY + "px"
           } else {
               targElem.style.left = evt.clientX - offsetX + "px"
               targElem.style.top = evt.clientY - offsetY + "px"
           }

return false

       }
   }

} function engage(evt) {

   evt = (evt) ? evt : (window.event) ? window.event : ""
   var targElem = (evt.target) ? evt.target : evt.srcElement
   if (targElem.className == "draggable") {
       while (targElem.id != "myLayer" && targElem.parentNode) {
           targElem = targElem.parentNode
       }
       if (targElem.id == "myLayer") {
           engaged = true
           if (evt.pageX) {
               offsetX = evt.pageX - targElem.offsetLeft
               offsetY = evt.pageY - targElem.offsetTop        
           } else {
               offsetX = evt.offsetX - document.body.scrollLeft
               offsetY = evt.offsetY - document.body.scrollTop
               if (navigator.userAgent.indexOf("Win") == -1) {
                   offsetX += document.body.scrollLeft
                   offsetY += document.body.scrollTop
                  }
   
           }
           return false
       }
   }

} function release(evt) {

   evt = (evt) ? evt : (window.event) ? window.event : ""
   var targElem = (evt.target) ? evt.target : evt.srcElement
   if (targElem.className == "draggable") {
       while (targElem.id != "myLayer" && targElem.parentNode) {
           targElem = targElem.parentNode
       }
       if (engaged && targElem.id == "myLayer") {
           engaged = false
       }
   }

} </SCRIPT> </HEAD> <BODY>

Dragging a Layer


   Drag me around the window.

</LAYER> <SCRIPT LANGUAGE="JavaScript"> document.onmousedown = engage document.onmouseup = release document.onmousemove = dragIt document.onmouseout = release </SCRIPT> </BODY> </HTML>

      </source>
   
  


Hide and show layer

   <source lang="html4strict">

/* JavaScript Application Cookbook By Jerry Bradenbaugh Publisher: O"Reilly Series: Cookbooks ISBN: 1-56592-577-7

  • /

<HTML> <HEAD> <TITLE>dhtml.js example</TITLE> <SCRIPT LANGUAGE="JavaScript1.2"> // dhtml.js // Set browser-determined global variables var NN = (document.layers ? true : false); var hideName = (NN ? "hide" : "hidden"); var showName = (NN ? "show" : "visible"); var zIdx = -1; function genLayer(sName, sLeft, sTop, sWdh, sHgt, sVis, copy) {

 if (NN) {
   document.writeln("<LAYER NAME="" + sName + "" LEFT=" + sLeft + " TOP=" + sTop + 
   " WIDTH=" + sWdh + " HEIGHT=" + sHgt + " VISIBILITY="" + sVis + """ + 
   " z-Index=" + zIdx + ">" + copy + "</LAYER>");
   }
 else {
document.writeln("
" + copy + "
"
     );
   }
 }

// Define a function to hide layers function hideSlide(name) {

 refSlide(name).visibility = hideName;
 }

// Define a function to reveal layers function showSlide(name) {

 refSlide(name).visibility = showName;
 }

// Define a central function to reference layers function refSlide(name) {

 if (NN) { return document.layers[name]; }
 else { return eval("document.all." + name + ".style"); }
 }

</SCRIPT> </HEAD> <BODY> [<A HREF="javascript: hideSlide("myLayer");">Hide</A>] [<A HREF="javascript: showSlide("myLayer");">Show</A>] <SCRIPT LANGUAGE="JavaScript1.2">

</SCRIPT> </BODY> </HTML>

      </source>
   
  


"layer" and "ilayer" Tag Properties

   <source lang="html4strict">

Property Description above A Layer object higher in z-order of all layers in the document (null if the layer is topmost). background The URL of an image to use as the background for the layer. below A Layer object lower in z-order of all layers in the document (null if the layer is lowest). bgcolor The background color for the layer. clip Defines the clipping rectangle. Anything outside of this rectangle is clipped from view. height The height in pixels of the layer. left The x-axis position in pixels of the layer, relative to the origin of its parent layer. name The name of the layer. src The URL for the layer"s content source. top The y-axis position in pixels of the layer, relative to the origin of its parent layer. visibility Defines the layer"s visibility attributes. width The width in pixels of the layer. z-index The relative z-order of the layer, relative to its siblings and parent.

      </source>
   
  


Layer Background Colors (W3C)

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript"> function setColor(evt) {

   evt = (evt) ? evt : (window.event) ? window.event : ""
   if (evt) {
       var elem = (evt.target) ? evt.target : evt.srcElement
       if (elem.className == "palette") {
           document.getElementById("display").style.backgroundColor = elem.style.backgroundColor
       }
   }

} document.onmouseover = setColor </SCRIPT> </HEAD> <BODY>

Layer Background Colors (W3C)


<SCRIPT LANGUAGE="JavaScript"> var oneLayer var colorTop = 100 var colorLeft = 20 var colorWidth = 40 var colorHeight = 40 var colorPalette = new Array("aquamarine","coral","forestgreen",

                  "goldenrod","red","magenta","navy","teal")

for (var i = 0; i < colorPalette.length; i++) {

oneLayer = "
\n"
   document.write(oneLayer)

} </SCRIPT>

Some reversed text to test against background colors.

</BODY> </HTML>


      </source>
   
  


Layer seek

   <source lang="html4strict">

// Seek nested NN4 layer from string name function seekLayer(doc, name) {

   var theObj;
   for (var i = 0; i < doc.layers.length; i++) {
       if (doc.layers[i].name == name) {
           theObj = doc.layers[i];
           break;
       }
       // dive into nested layers if necessary
       if (doc.layers[i].document.layers.length > 0) {
           theObj = seekLayer(document.layers[i].document, name);
       }
   }
   return theObj;

} // Convert object name string or object reference // into a valid element object reference function getRawObject(obj) {

   var theObj;
   if (typeof obj == "string") {
       if (isW3C) {
           theObj = document.getElementById(obj);
       } else if (isIE4) {
           theObj = document.all(obj);
       } else if (isNN4) {
           theObj = seekLayer(document, obj);
       }
   } else {
       // pass through object reference
       theObj = obj;
   }
   return theObj;

}

      </source>
   
  


Layer "srcFilter" Example

   <source lang="html4strict">
   

<html> <head> <script language="JavaScript"> function function1() { myLayer.filters[0].Apply();

   if (myLayer.style.visibility == "visible") {
       myLayer.style.visibility = "hidden";
       myLayer.filters.revealTrans.transition = 2;
   } else {
       myLayer.style.visibility = "visible";
       myLayer.filters[0].revealTrans.transition = 3;
   }
   myLayer.filters[0].Play();
   var m = window.event.srcFilter;
   alert(m); 

} </script> </head> <body bottommargin="150">

   <img src="http://www.wbex.ru/style/logo.png" width="99" height="75">

<input type="button" id="myButton" onClick="function1();" value="Play Transition"> </body> </html>


     </source>
   
  


Methods and Properties of the Layer Object

   <source lang="html4strict">

/* JavaScript Unleashed, Third Edition by Richard Wagner and R. Allen Wyke ISBN: 067231763X Publisher Sams CopyRight 2000

+---------+----------------+-------------------------------------------------+

 Type       Item             Description

+---------+----------------+-------------------------------------------------+

 Method

+---------+----------------+-------------------------------------------------+

          captureEvents()   Specifies the event types to capture.

+---------+----------------+-------------------------------------------------+

          handleEvent()     Invokes handler for specified event.

+---------+----------------+-------------------------------------------------+

          load()            Loads a new URL.

+---------+----------------+-------------------------------------------------+

          moveAbove()       Moves the layer above another layer.

+---------+----------------+-------------------------------------------------+

          moveBelow()       Moves the layer below another layer.

+---------+----------------+-------------------------------------------------+

          moveBy()          Moves the layer to a specified position.

+---------+----------------+-------------------------------------------------+

          moveTo()          Moves the top-left corner of the window to the 
                            specified screen coordinates.

+---------+----------------+-------------------------------------------------+

         moveToAbsolute()   Changes the layer position to the specified pixel 
                            coordinates within the page.

+---------+----------------+-------------------------------------------------+

          releaseEvents()   Sets the layer to release captured events of the 
                            specified type.

+---------+----------------+-------------------------------------------------+

          resizeBy()        Resizes the layer by the specified height and 
                            width values.

+---------+----------------+-------------------------------------------------+

          resizeTo()        Resizes the layer to have the specified height and 
                            width values.

+---------+----------------+-------------------------------------------------+

          routeEvent()      Passes a captured event along the normal event hierarchy.

+---------+----------------+-------------------------------------------------+

Property

+---------+----------------+-------------------------------------------------+

          above             Specifies the layer above.

+---------+----------------+-------------------------------------------------+

          background        Refers to the background image of the layer.

+---------+----------------+-------------------------------------------------+

          below             Specifies the layer below.

+---------+----------------+-------------------------------------------------+

          bgColor           Refers to the background color of the layer.

+---------+----------------+-------------------------------------------------+

          clip.bottom       Refers to the bottom of the layer"s clipping area.

+---------+----------------+-------------------------------------------------+

          clip.height       Refers to the height of the layer"s clipping area.

+---------+----------------+-------------------------------------------------+

          clip.left         Refers to the left of the layer"s clipping area.

+---------+----------------+-------------------------------------------------+

          clip.right        Refers to the right of the layer"s clipping area.

+---------+----------------+-------------------------------------------------+

          clip.top          Refers to the top of the layer"s clipping area.

+---------+----------------+-------------------------------------------------+

          clip.width        Refers to the width of the layer"s clipping area.

+---------+----------------+-------------------------------------------------+

          document          Refers to the Document object that contains the layer.

+---------+----------------+-------------------------------------------------+

          left              Refers to the x-coordinate of the layer.

+---------+----------------+-------------------------------------------------+

          name              Refers to the name of the layer.

+---------+----------------+-------------------------------------------------+

          pageX             Refers to the x-coordinate relative to the document.

+---------+----------------+-------------------------------------------------+

          pageY             Refers to the y-coordinate relative to the document.

+---------+----------------+-------------------------------------------------+

          parentLayer       Refers to the containing layer.

+---------+----------------+-------------------------------------------------+

          siblingAbove      Refers to the layer above in the zIndex.

+---------+----------------+-------------------------------------------------+

          siblingBelow      Refers to the layer below in the zIndex.

+---------+----------------+-------------------------------------------------+

          src               Refers to the source URL for the layer.

+---------+----------------+-------------------------------------------------+

          top               Refers to the y-coordinate of the layer.

+---------+----------------+-------------------------------------------------+

          visibility        Refers to the visibility state of the layer.

+---------+----------------+-------------------------------------------------+

          window            Refers to the Window or Frame object that contains 
                            the layer.

+---------+----------------+-------------------------------------------------+

          x                 Refers to the x-coordinate of the layer.

+---------+----------------+-------------------------------------------------+

          y                 Refers to the y-coordinate of the layer.

+---------+----------------+-------------------------------------------------+

          z                 Refers to the relative z-order of this layer with 
                            respect to its siblings.

+---------+----------------+-------------------------------------------------+

  • /
      </source>
   
  


Monitors divisions (or layers) on dynamic Web pages (DHTML)

   <source lang="html4strict">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML>

 <HEAD>
   <TITLE>JsLib 1.3 - Exemple - dyna.js</TITLE>
   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
   <META NAME="Author" CONTENT="Etienne CHEVILLARD">
   
   <SCRIPT TYPE="text/javascript" LANGUAGE="Javascript">

/* dyna.js

* Role : controle les divisions des pages Web dynamiques
* Projet : JsLib
* Auteur : Etienne CHEVILLARD (echevillard@users.sourceforge.net)
* Version : 1.3
* Creation : 07/07/2001
* Mise a jour : 23/02/2005
* Bogues connues : - Opera 5/6 ne gere pas la couleur de fond "transparent"
*                  - Opera 5/6 ne gere pas la modification du contenu des divisions
*/

// --- Variables globales --- // choix du DOM (Document Object Model) var dyna_w3=0; // DOM-1 du W3C : Mozilla, Netscape 6/7, IE 5/6, Opera 7, Safari var dyna_ie=0; // IE 4 var dyna_nn=0; // Netscape Navigator 4 var dyna_op=0; // Opera 4/5/6 // determine le DOM utilise par le navigateur if (document.getElementById && document.getElementsByTagName)

 dyna_w3=1;

else if (document.all && navigator.userAgent.toLowerCase().indexOf("opera")!=-1)

 dyna_op=1;

else if (document.all)

 dyna_ie=1;

else if (document.layers)

 dyna_nn=1;

// recharge la page si redimensionnement de la fenetre sous Netscape 4 (bogue) window.onresize=function () {

 if (dyna_nn) { history.go(0); }

} // --- Fonctions --- // parcoure les divisions du DOM Netscape 4 pour trouver celle souhaitee function dyna_obtenirDivNN4(objet, nom) {

 var divs=objet.layers;
 var divTrouvee;
 for (var i=0; i<divs.length; i++) {
   if (divs[i].id==nom)
      divTrouvee=divs[i];
   else if (divs[i].layers.length > 0)
     var tmp=dyna_obtenirDivNN4(divs[i], nom);
   if (tmp)
     divTrouvee=tmp;
 }
 return divTrouvee;

} // fin dyna_obtenirDivNN4(objet, nom) // indique si le navigateur accepte le DHTML function accepteDHTML() {

 return (dyna_w3 || dyna_ie || dyna_nn || dyna_op);

} // fin accepteDHTML() // rend invisible la division specifiee function cacherDivision(id) {

 var ldiv=obtenirDivision(id);
 if (!ldiv)
   return false;
 if (dyna_w3 || dyna_ie || dyna_op)
   ldiv.style.visibility="hidden";
 else if (dyna_nn)
   ldiv.visibility="hide";
 return true;

} // fin cacherDivision(id) // cree une nouvelle division et l"ajoute au DOM // -- merci a Victor Lopes (victor3.lopes@voila.fr) function creerDivision(id, x, y, largeur, hauteur) {

 if ((!id) || (id=="") || (obtenirDivision(id)))
   return false;
 if (isNaN(x))
   x=0;
 if (isNaN(y))
   y=0;
 if (isNaN(largeur) || (largeur<0))
   largeur=0;
 if (isNaN(hauteur) || (hauteur<0))
   hauteur=0;
 if (dyna_w3 && document.createElement) {
   var ndiv=document.createElement("DIV");
   ndiv.id=id;
   ndiv.style.position="absolute";
   ndiv.style.visibility="hidden";
   ndiv.style.left=x;
   ndiv.style.top=y;
   ndiv.style.width=largeur;
   ndiv.style.height=hauteur;
   ndiv.style.zIndex=0;
   document.body.appendChild(ndiv);
 } else if (dyna_ie || dyna_op) {
var html="