JQ操作DOM练习1

280 阅读1分钟

一. 使用JQ制作一个5*5的table表格,并让每块表格显示不一样的背景颜色,以及鼠标点击时触发的效果?

1.首先使用document.createElement创建一个table标签、再for循环使用document.createElement创建多个tr标签,然后再for循环使用document.createElement创建多个td标签,(并且使用appendChild将节点添加)最后在td内设置一个鼠标点击时触发的效果,并使用firstElementChild、lastElementChild、previousElementSibling和nextElementSibling来给各个td添加不同的北京颜色,当表格设置完成后将节点加入到页面。

<script>
    let table = document.createElement('table');
    for (let i = 1; i <= 5; i++) {
        let td = document.createElement('tr');
        table.appendChild(tr)
        for (let j = 1; j <= 5; j++) {
            let td = document.createElement('td');
            td.innerHTML = i * j
            td.onclick = function() {
                let tds = document.getElementsByTagName('td');
                for (let i = 0; i < tds.lenght; i++) {
                    tds[i].style.color = '#000',
                    tds[i].style.fontSize = '16px'
                }
                this.style.color = '#f00'
                this.style.fontSize = '20px'
            }
            tr.appendChild(td)
        }
    }
    table.classList.add('tb')
    table.classList.add('zz')
    
    table.firstElementChild.firstElementChild.style.background = 'lightpink'
    table.firstElementChild.lastElementChild.style.background = 'lightgreen'
    
    table.firstElementChild.firstElementChild.nextElementSibling.style.background = '#c2b4'
    table.firstElementChild.lastElementChild.previousElementSibling.style.background = '#fba51a'
    table.firstElementChild.lastElementChild.previousElementSibling.previousElementSibling.style.background = 'black'
    table.firstElementChild.lastElementChild.previousElementSibling.previousElementSibling.style.color = 'white'
    
    table.firstElementChild.nextElementSibling.style.background = '#512abd'
    table.firstElementChild.nextElementSibling.style.color = 'white'
    
    table.firstElementChild.nextElementSibling.nextElementSibling.lastElementChild.previousElementSibling.previousElementSibling.style.background = 'lightgreen'
    
    
    
    table.lastElementChild.firstElementChild.style.background = '#d46'
    table.lastElementChild.lastElementChild.style.background = 'lightpink'

    table.lastElementChild.firstElementChild.nextElementSibling.style.background = '#fba51a'
    table.lastElementChild.lastElementChild.previousElementSibling.style.background = '#c2b4'
    table.lastElementChild.lastElementChild.previousElementSibling.previousElementSibling.style.background = 'black'
    table.lastElementChild.lastElementChild.previousElementSibling.previousElementSibling.style.color = 'white'

    table.lastElementChild.previousElementSibling.style.background = '#f461aa'

     document.body.appendChild(table)  // 放在末尾,先让内容准备好,然后直接存table里
</script>

预览效果,红色字体为点击事件触发后的样式