Javascript DOM 编程艺术(第2版)学习记录之第四章JS图片库

本章所涉及的一些知识点:
setAttribute getAttribute this onclick
childNodes nodeType nodeValue firstChild lastChild

为这些图片创建一个链接清单




    
    Title
    


    

Snapshots

![](images/IMG_0505.JPG) //占位符

Choose an image.

为了把“占位符”图片替换为想要查看的图片,需要改变其src属性。
function show(whicpic)
whichpic代表着一个元素节点,更具体地说,是一个指向某个图片的元素
whichpic.getAttribute("href")
把这个路径存入变量source
var source = whichpic.getAttribute("href")
获取占位符图片
var placeholder = document.getElementById("placeholder")
placeholder.setAttribute("src" , source)

function showPic(whichpic) {                        //修改占位符图片
    var source = whichpic.getAttribute("href");
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src",source);
}

事件处理函数的作用是,在特定事件发生时调用特定的javascript代码。
showpic()函数需要一个带有href属性的元素节点参数,
使用this关键词,表示“这个
元素节点”
onclick = "showpic(this) ; return false"
在onclick事件处理函数所触发的Javascript代码返回给它false的值,即这个链接的默认行为没有被触发

  • Wind
  • purple
  • olive
  • red
  • 在一颗节点树上,childNodes属性可以用来获取任何一个元素的所有子元素,是一个包含这个元素全部子元素的数组。elements.childNodes

    function countBodyChild(){   
    var body_element = document.getElementsByTagName("body")[0]
    alert(body_element.childNodes.length)
    alert(body_element.nodeType)
    window.onload = countBodyChild 
    

    childNodes[0] = firstChild
    这里[0]是body的第一个元素,整篇html也且只有一个用[0]是获取body元素,不用的话只是获取一个空的数组
    元素节点的nodeType属性值是1
    属性节点的nodeType属性值是2
    文本节点的nodeType属性值是3

    在图片链接被点击时,为了能动态地用图片的title替换掉图片说明,需要对showpic()做修改
    获取whichpic对象的title属性值

    var text = whichpic.getAttribute("title")
    var description = document.getElementById("description")
    

    想改变一个文本节点的值,可以使用DOM提供的nodeValue属性
    假如你使用description.nodeValue,将会返回一个null值,

    元素本身的nodeValue属性是一个空值
    真正需要的是

    元素说包含的文本的值

    description.childNodes[0].nodeValue

    nodeValue属性的用途不仅可以用来检索节点的值,还可以用来设置节点的值。

    var description = document.getElementById("description")
    description.firstChild.nodeValue = text```
    
    
    添加一些css样式后,一个较为美观的JS图片库就做出来了。
    
    
    

    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
    }

    
    

    你可能感兴趣的:(Javascript DOM 编程艺术(第2版)学习记录之第四章JS图片库)