在网页上实现图片与文字的替换

运用DOM的五个常用方法

1.getElementById;

2.getElementsByTagName;

3.getElementByClassName;

4.getAttribute;

5.setAttribute;

来进行图片的替换

 whichpic.getAttribute("href");
 var source = whichpic.getAttribute("href");
/* document.getElementById("placeholder");*/
 var placeholder = document.getElementById("placeholder");
 placeholder.setAttribute("src",source);
具体实现js代码。

进行文字的替换

DOM属性

1.childNodes; 

2.nodeType;

3.nodeValue;

4.firstChild;

5.lastChild;

var text = whichpic.getAttribute("title");
var description = document.getElementById("description");
description.firstChild.nodeValue = text;
实现代码。

整体代码

html部分

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Image Gallery</title>
    <link href="layout.css" type="text/css" rel="stylesheet" media="screen">
</head>
<body>
<h1>Snapshots</h1>
<ul>
    <li>
        <a href="11.jpg" onclick="showPic(this); return false;" title="first lady">First Lady</a>
    </li><!--添加return false 是防止点击事件出发后被转到原来界面-->
    <li>
        <a href="12.jpg" onclick="showPic(this); return false;" title="second lady">Second Lady</a>
    </li>
    <li>
        <a href="13.jpg" onclick="showPic(this); return false;" title="third lady">Third Lady</a>
    </li>
    <li>
        <a href="14.jpg" onclick="showPic(this); return false;" title="forth lady">Forth Lady</a>
    </li>

</ul>
<img id="placeholder" src="15.jpg" alt=" my image gallery">
<p id="description">Choose an image.</p>
<script  type="text/javascript"  src="01.js"></script>
</body>
</html>
js部分

/**
 * Created by Administrator on 2015/9/1.
 */
function showPic(whichpic){
    whichpic.getAttribute("href");
    var source = whichpic.getAttribute("href");
   /* document.getElementById("placeholder");*/
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src",source);
    var text = whichpic.getAttribute("title");
    var description = document.getElementById("description");
    description.firstChild.nodeValue = text;
}

function countBodyChildren(){
    var body_element = document.getElementsByTagName("body")[0];
/*    alert(body_element.childNodes.length);*/
    alert(body_element.nodeType);
}
/*window.onload = countBodyChildren;*/
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;
}

posted on 2015-09-01 23:35  franeu  阅读(183)  评论(0编辑  收藏  举报