您的位置:首页 > Web前端 > JavaScript

JavaScript 简单应用

2015-01-13 12:39 267 查看

JavaScript 简单应用

 

一:简介

 

        此笔记是对《JavaScript权威指南》第4章内容的概括、重点的记录。不是重现书本实例。书中大部分实例放在github上、有兴趣的也可以看这本书或者github上代码。github地址会放在JavaScript目录中。

 

二:JavaScript应用步骤

 

        1.  编写JavaScript脚本

        2.  在页面中引用:

                a)可以直接在页面中使用<script>标签将JavaScript相关内容放入其中。

                b)可以将脚本放入一个或者多个文件结尾为js的文件中、在需要使用的页面中引入。

 

 

三:实例简述

 

        网页中有多个链接、不点击任何链接时、页面下方的显示位置会显示一张默认图片和默认说明、当点击某个具体链接时将下方显示位置的默认图片替换成链接定向到的图片、同时将链接的说明内容显示在指定位置。

 

四:实例实现关键点

 

        1. 获取a链接的herf和title属性。

        2. 为所有链接添加单击事件。

        3. 阻止链接默认行为。

        2. 修改默认图片标签的src和说明标签内的文本内容。

 

五:相关方法与解决方式

   

    1.阻止a默认行为:

 <li><a onclick="switchPicture(this); return false" href="../picture/chenhong.jpg" title="Chen hong">Chen hong</a></li>
    2.相关方法

 function switchPicture (whichPicture) {
var source = whichPicture.href;
var placeholder = document.getElementById('placeholder');
placeholder.setAttribute('src', source);
document.getElementById('description').firstChild.nodeValue = whichPicture.getAttribute('title');
}

六:补充

 

    效果:

 


    showPicture.js:

function switchPicture (whichPicture) {
var source = whichPicture.href;
var placeholder = document.getElementById('placeholder');
placeholder.setAttribute('src', source);
document.getElementById('description').firstChild.nodeValue = whichPicture.getAttribute('title');
}

/*
function countBodyChildren () {
alert(document.getElementsByTagName('body')[0].childNodes.length);
}

window.onload = countBodyChildren;*/

    showPicture.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Show Picture</title>
<script src="../js/showPicture.js" ></script>
<link rel="stylesheet" href="../style/showPicture.css">
</head>
<body>
<h1>Snapshots</h1>
<ul>
<li><a onclick="switchPicture(this); return false" href="../picture/chenhong.jpg" title="Chen hong">Chen hong</a></li>
<li><a onclick="switchPicture(this); return false" href="../picture/liuyan.jpg" title="Liu Yan">Liu Yan</a></li>
<li><a onclick="switchPicture(this); return false" href="../picture/liuyifei.jpg" title="Liu Yi Fei">Liu Yi Fei</a></li>
<li><a onclick="switchPicture(this); return false" href="../picture/shishi.jpg" title="Liu Shi Shi">Liu Shi Shi</a></li>
</ul>
<img src="../picture/benchi.jpg" alt="my image gallery" id="placeholder">
<p id="description">Choose one picture!</p>
</body>
</html>
    showPicture.css:

body {
font-family: "Helvetica", "Arial", serif;
color: #333;
background-color: #ccc;
margin: 1em 10%;
}

h1 {
color: #333;
background-color: transparent;
}

a {
color: #c60;
background-color: transparent;
font-weight: bold;
text-decoration: none;
}

ul {
padding: 0;
}

li {
float: left;
padding: 1em;
list-style: none;
}

img {
display: block;
clear: both;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息