首页 > Ajax > Js学习笔记之几个简单的Js应用

Js学习笔记之几个简单的Js应用

1、Js实现下拉菜单功能

      实现的大致思路,预先设置下拉的详细菜单style.display为none,主菜单创建onmouseover的事件,实现鼠标移到主菜单上,下拉的详细菜单style.display变为block,当鼠标离开菜单区域,详细菜单又变为隐藏状态。

     HTML部分:

    <h1>Shakespeare’s Play</h1>
   <div>
     <a href=”menu1.html”>Comedies</a>
  <ul id=”menu1″>
    <li><a href=”pg1.html”>All’s Well That Ends Well</a></li>
    <li><a href=”pg2.html”>As You Like It</a></li>
       <li><a href=”pg3.html”>Love’s Labour’s Lost</a></li>
    <li><a href=”pg4.html”>The Comedy of Errors</a></li>
   </ul>
 </div>
 <div>
     <a href=”menu2.html”>Tragedies</a>
  <ul id=”menu2″>
    <li><a href=”pg5.html”>Anthony Cleopatra</a></li>
    <li><a href=”pg6.html”>Hamlet</a></li>
       <li><a href=”pg7.html”>Romeo Juilet</a></li>   
   </ul>
 </div>
 <div>
     <a href=”menu3.html”>Histories</a>
  <ul id=”menu3″>
    <li><a href=”pg8.html”>Henry IV,Part 1</a></li>
    <li><a href=”pg9.html”>Henry IV,Part 2</a></li>      
   </ul>
 </div>

  Javascript部分:

window.onload = initAll;

function initAll() {
 var allLinks = document.getElementsByTagName(“a”);

 for (var i=0;i<allLinks.length;i++)
 {
  if (allLinks[i].className.indexOf(“menuLink”)>-1)
  {
   allLinks[i].onclick = function() {return false;};
   allLinks[i].onmouseover = toggleMenu;
  }
 }
}

function toggleMenu() {
 var startMenu = this.href.lastIndexOf(“/”)+1;
 var stopMenu = this.href.lastIndexOf(“.”);
 var thisMenuName = this.href.substring(startMenu,stopMenu);

 document.getElementById(thisMenuName).style.display = “block”;

 this.parentNode.className = thisMenuName;   // we assign a class to the parent of the current link,just to div
 this.parentNode.onmouseout = toggleDivOff;  // and we assign onmouseover and onmouseout handlers to the div
 this.parentNode.onmouseover = toggleDivOn; // this is very important
}

function toggleDivOn() {
 document.getElementById(this.className).style.display = “block”;
 }

function toggleDivOff() {
 document.getElementById(this.className).style.display = “none”;
}

    在鼠标还在div的活动范围内中 ,必须让下拉菜单处于显示状态。

2、实现图片幻灯片轮播

      这个相对来说比较简单,预先把图片和要显示的文字存储到数组里(很遗憾,书里面的图片没有这么做,而是以slideImg1/slideImg2这样来命名的,不过问题不大),然后把事件绑定到往前和往后的2个按钮上,就可以了。要注意的就是,往前或者往后到头了记得再做次循环,下面来看看代码。

      HTML部分:

   <body>
   <h1>Our Summer Vocation SlideShow</h1>
   <img width=320 src=”images/slideImg0.jpg” alt=”Our Vacation Pix” id=”slideshow” />
   <div id=”imgText”>&nbsp;</div>
   <br clear=”all” />
   <form action=”#”>
      <input type=button id=”prevLink” value=”&laquo; Previous” />
   <input type=button id=”nextLink” value=”Next &raquo;” />
   </form>
  </body>

    Javascript部分:

window.onload = initAll;

var currImg = 0;

var captionText = new Array(
   “Our ship,leaving Vancouver,”,
   “We took a helicopter ride at our first port,Juneau.”,
   “The helicopter took us to Mendenhall Glacier.”,
   “The happy couple,on the glacier.”,
   “It’s nice to go on vocation,but it’s nice to be home again,too.”
   );

 function initAll() {
  document.getElementById(“imgText”).innerHTML = captionText[0];
  document.getElementById(“prevLink”).onclick = processPrevious;
  document.getElementById(“nextLink”).onclick = processNext;
 }

 function processPrevious() {
  newSlide(-1);
 }

 function processNext() {
  newSlide(1);
 }

 function newSlide(direction) {
  var imgCt = captionText.length;

  currImg = currImg + direction;
  if (currImg<0)
  {
   currImg = imgCt-1;
  }
  if (currImg == imgCt)
  {
   currImg = 0;
  }
  document.getElementById(“slideshow”).src = “images/slideImg”+currImg+”.jpg”;
  document.getElementById(“imgText”).innerHTML = captionText[currImg];
 }

3、用Js画简单的柱形图

         刚开始看到这个标题 Bar Graph 我着实吓了一跳,这么快就到那么深入的部分了啊,结果仔细一看,作者用了一个小技巧来实现画图的部分。下面我大致总结一下这个部分的一些技巧:

 1)首先使用了Js的对象,把原始二维表的数据都存储到了这个对象的某个属性中。

        We create the jsChart object and assign values to the properties.Note that we’re not using the var keyword before each of these;that’s because they aren’t new variables.Instead,they’re new properties that we’re adding to an existing variable.

2)  原始二维表的数据用两个for循环来读取,横向和竖向则为2个field。

3)图标的绘画部分是这样的,首先创建一个像素图片,大小1*1,然后柱状图就是这个图片,只是我们把高度和数据关联了起来,高度为具体数据的3倍(这个根据具体案例来定)

       Each of these is a single-pixel GIF in its corresonding color.HTML allows you to set the height and width regardless of the image’s actual physical dimensions,so a single pixel allows us to create bars of any size and shape.

      HTML部分:

<style>
  body {
     background-color:white;
     color:black;
     font:12px;
  }

  form {
      float:left;
   width:200px;
  }

  .vert {
     text-align:center;
  vertical-align: bottom;
  }

   .horiz {
      padding:5px;
  }

 th.vert {
     border-left:1px black solid;
  border-bottom:1px black solid;
  vertical-align:middle;
  text-align:left;
  font-size:16px;
 }

 th.horiz {
     border-left:1px black solid;  
  vertical-align:middle;
  text-align:left;
  font-size:16px;
 }

</style>
<body>
<form action=”#”>
   Choose a chart<br />
   <input type=radio name=”type” value=”browser” checked=”checked” /> Browser Usage<br />
   <input type=radio name=”type” value=”platform” />
   Javascript Usage<br />
   <p><br /></p>
   Choose a color<br />
   <input type=radio name=”color” value=”lilRed.gif” checked=”checked” />&nbsp;Red<br />
   <input type=radio name=”color” value=”lilGreen.gif” /> Green<br />
   <input type=radio name=”color” value=”lilBlue.gif” /> Blue<br />
    <p><br /></p>
 Choose a direction<br />
   <input type=radio name=”direction” value=”horizontal” checked=”checked” /> Horizontal<br />
   <input type=radio name=”direction” value=”vertical” /> Vertical<br />
</form>
<div id=”chartArea”>&nbsp;</div>
</body>

     Javascript部分:

window.onload = initAll;

function initAll() {
 var radioButtons = document.getElementsByTagName(“input”);

 for (var i=0;i<radioButtons.length;i++ )
 {
  if (radioButtons[i].type == “radio”)
  {
   radioButtons[i].onclick = chgChart;
  }
 }
 chgChart();
}

function chgChart() {
 var bChart = new Object();
 bChart.name = “Browser usage by year”;
 bChart.years = new Array(“1998″,”1999″,”2000″,”2001″,”2002″,”2003″,”2004″,”2005″,”2006″);
 bChart.fieldnames = new Array(“Netscape”,”MSIE”,”Other”);
 bChart.field1 = new Array(38.9,31.9,21.2,12.4,6.6,5.1,3,1,6);
    bChart.field2 = new Array(60.6,67.4,78.3,85.6,92.5,94.0,92,89,90);
 bChart.field3 = new Array(0.5,0.5,0.5,2.1,0.9,1.0,4,9,3);
 bChart.fields = new Array(bChart.field1,bChart.field2,bChart.field3);

 var jsChart = new Object();
 jsChart.name = “JavaScript usage by year”;
 jsChart.years = new Array(“1998″,”1999″,”2000″,”2001″,”2002″,”2003″,”2004″,”2005″,”2006″);
 jsChart.fieldnames = new Array(“1.2 or later”,”1.0-1.1″,”No Javascript”);
 jsChart.field1 = new Array(63.4,66.5,78.4,80.2,88.1,89.1,94,89,96);
 jsChart.field2 = new Array(18.7,12.6,2.8,0.8,0.3,0.3,0,0,0);
 jsChart.field3 = new Array(17.9,21.0,18.8,19.0,11.6,10.6,4,9,3);
 jsChart.fields = new Array(jsChart.field1,jsChart.field2,jsChart.field3);

 var radioButtons = document.getElementsByTagName(“input”);
 var currDirection= getButton(“direction”);
 var imgSrc = “images/”+getButton(“color”);
 var thisChart = (getButton(“type”)==”browser”)?bChart:jsChart;

 var chartBody = “<h2>”+thisChart.name+”</h2><table>”;

 for (var i=0;i<thisChart.years.length;i++)
 {
  if (currDirection==”horizontal”)
  {
   chartBody += “<tr><th rowspan=4 class=’horiz’>”+thisChart.years[i];
   chartBody += “</th><td colspan=’2′></td></tr>”;
   for (var j=0;j<thisChart.fieldnames.length;j++)
   {
    chartBody += “<tr><td class=’horiz’>”+thisChart.fieldnames[j];
    chartBody += “</td><td><img src=’”+imgSrc+”‘ height=’15′ width=’”;
    chartBody += thisChart.fields[j][i]*3+”‘ alt=’horiz bar’ />”;
    chartBody += “&nbsp;&nbsp;”+thisChart.fields[j][i]+”</td></tr>”;
   }
  }
  else {
   chartBody += “<tr><th rowspan=’2′ class=’vert’>”+thisChart.years[i]+”<th>”;
   for (var j=0;j<thisChart.fieldnames.length;j++)
   {
    chartBody += “<td class=’vert’><img src=’”+imgSrc;
    chartBody += “‘ alt=’vert bar’ hspace=’10′ width=’15′ height=’”;
    chartBody += thisChart.fields[j][i]*3+”‘ /></td>”;
   }
   chartBody += “</tr><tr>”;
   for (j=0;j<thisChart.fieldnames.length;j++)
   {
    chartBody += “<td class=’vert’>”+thisChart.fields[j][i]+”<br />”;
    chartBody += thisChart.fieldnames[j]+”<br /><bt /></td>”;
    }
    chartBody += “</tr>”;
  }
 }

    chartBody += “</table>”;
 document.getElementById(“chartArea”).innerHTML = chartBody;

 function getButton(buttonSet) {
  for (var i=0;i<radioButtons.length;i++)
  {
   if (radioButtons[i].name == buttonSet && radioButtons[i].checked)
   {
    return radioButtons[i].value;
   }
  }
  return -1;
 }
}

4、用cookie存储用户的样式偏好

        这个例子主要是通过用户的单击按钮来切换样式,预先设置了不同的2个样式文件,并且通过cookie存储用户喜欢的样式文件名称,以便下次打开时直接引用。

        主要设计思路是,用户打开页面时检查cookie,预先有没有存储过的style文件名,而关闭页面的时候则提取当前激活的style文件并存储到cookie中去,当按下按钮时和检查cookie发现有预先设置的cookie时,用一个方法来设置当前有效的style文件。

        此例同样用到了js对象的properties,不同的是它主要是读取,使用getAttribute()方法来读取,另外如果禁用一个外部css文件的链接,直接把disablue值设为false就可以了。

        HTML部分:

<head>
<title>Style Changer</title>
<link href=”script17.css” rel=”stylesheet” rev=”stylesheet” />
<link href=”sansStyle.css” rel=”stylesheet” rev=”stylesheet” title=”defalut” />
<link href=”serifStyle.css” rel=”alternate stylesheet” rev=”alternate stylesheet” title=”serif” />
<script type=”text/javascript” language=javascript src=”script17.js”></script>
</head>

<body>
  <div><p>Change your font:</p>
   <form action=”#”>
     <input type=button value=”Sm Sans” id=”default” />&nbsp;&nbsp;
  <input type=button value=”Lg Serif” id=”serif” />
 </form>
 <br clear=”all” />
 </div>
 <p>Filing traditionally has been performed by visiting a clerk at a filing window, paying a filing fee by cash, check, or credit card, and submitting the document to be filed in duplicate or even triplicate. For each document filed, the court clerk inspects the document to ensure compliance with the court’s rules on how legal documents should be formatted, verifies that the filer has not been declared a vexatious litigant, and confirms that the case number and caption are for a valid case. Next, the court clerk then stamps both copies with a large stamp that indicates the name of the court and the date the document was filed, then keeps one copy for the court’s files and returns one copy to the filer for the filer’s own records. In courts that require triplicate submissions, the third copy is then taken (either by the clerk or by the filer) to the chambers or courtroom of the judge assigned to the case. The clerk then adds the document to the docket for the case as well as any related deadlines or events.</p><h1>Now the effective css is:</h1>
<div id = “effectiveclass”></div></body>

        Javascript部分:

window.onload = initStyle;
window.onunload = unloadStyle;

function initStyle() {
 var thisCookie = cookieVal(“style”);
 var title =(thisCookie)?thisCookie:getPreferredStylesheet();
 setActiveStylesheet(title);

 var allButtons = document.getElementsByTagName(“input”);
 for (var i=0;i<allButtons.length ;i++ )
 {
  if (allButtons[i].type == “button”)
  {
   allButtons[i].onclick = setActiveStylesheet;
  }
 }
}

function unloadStyle() {
 var expireDate = new Date();
 expireDate.setYear(expireDate.getFullYear()+1);
 document.cookie = “style=”+getActiveStylesheet()+”;expires=”+expireDate.toGMTString()+”;path=/”;
}

function getPreferredStylesheet() {
 var thisLink,relAttribute;
 var linksFound = document.getElementsByTagName(“link”);
 for (var i=0;i<linksFound.length;i++ )
 {
  thisLink = linksFound[i];
  relAttribute = thisLink.getAttribute(“rel”);
  if (relAttribute.indexOf(“alt”) == -1&& relAttribute.indexOf(“alt”)==-1 && thisLink.getAttribute(“title”))
  {
   return thisLink.getAttribute(“title”);
  }
 }
 return “”;
}

function getActiveStylesheet() {
 var thisLink;
 var linksFound = document.getElementsByTagName(“link”);

 for (var i=0;i<linksFound.length;i++)
 {
  thisLink = linksFound[i];
  if (thisLink.getAttribute(“rel”).indexOf(“style”)>-1&& thisLink.getAttribute(“title”) && !thisLink.disabled)
  {
   return thisLink.getAttribute(“title”);
  }
 }
 return “”;
}

function setActiveStylesheet(inVal) {
 var thisLink;
 var linksFound = document.getElementsByTagName(“link”);

 var title = (inVal)?((typeof inVal==”string”)?inVal:inVal.target.id):window.event.srcElement.id;
 for (var i=0;i<linksFound.length;i++ )
 {
  thisLink = linksFound[i];
  if (thisLink.getAttribute(“rel”).indexOf(“style”)>-1 && thisLink.getAttribute(“title”))
  {
   thisLink.disabled = true;
   if (thisLink.getAttribute(“title”) == title)
   {
    document.getElementById(“effectiveclass”).innerHTML = title;
    thisLink.disabled = false;
   }
  }
 }
}

function cookieVal(cookieName) {
 var thisCookie = document.cookie.split(“; “);
 for (var i=0;i<thisCookie.length;i++ )
 {
  if (cookieName == thisCookie[i].split(“=”)[0])
  {
   return thisCookie[i].split(“=”)[1];
  }
 }
 return “”;
}

       这里值得注意的一个方法setActiveStyleSheet,其在2个地方被用到,获取cookie时设置,这个很简单,title肯定有值,直接设置就可以了,在按钮触发的时候也会被用到,而在Firefox中方法的参数值其实是存在的,只是它不是string类型,所以存在这个判断:

var title = (inVal)?((typeof inVal==”string”)?inVal:inVal.target.id):window.event.srcElement.id;

       看下原版的英文解释:

        As seen above,when the user loads this page,the setActiveStylesheet() function is called and passed a parameter that’s referred to inside the function as inVal.When setActiveStyleSheet() is called after a button is clicked,however,there may or may not be a parameter passed,depending on which browser is being used and how it handles events.There are three possiblities:

1) initStyle() called this function and passed it a string containing the preferred stylesheet.

2)A style button was clicked in a browser that suppors W3C style events.In this case,inVal is automatically set to the event that triggered the function,so inVal will exist but it won’t be a string.When that happens,we know that the target of the event(what caused the event to trigger) is the button that was clicked,and the id of that button stores the style desired.

3) A style button was clicked in a browser that doesn’t support W3C standards(just like ie) but does support the IE event model.If that’s the case,the inVal variable won’t exist,so we instead grab the style desired from window.event.srcElement.id.

分类: Ajax 标签: ,
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.