简单说就是使用for循环将一组标签注册事件的算法
1.点击之后五个按钮的背景颜色变化为粉红色的效果,这样子先使用一个for循环将所有的按钮绑定事件,点击之后将所有按钮的背景颜色改编为无色,单独将点击的背景颜色换成粉红色。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button>按钮1</button> <button>按钮2</button> <button>按钮3</button> <button>按钮4</button> <button>按钮5</button> <script> var btns = document.getElementsByTagName('button'); for ( var i = 0 ; i < btns.length ; i ++ ) { btns[i].onclick = function ( ) { for ( var j = 0 ; j < btns.length ; j++ ) { btns[j].style.backgroundColor = '' ; } this.style.backgroundColor = 'pink' ; } } </script> </body> </html>
2.百度换肤案例
要注意的是最后那个图片的地址,使用的是 ‘++’
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } body { background: url(images/1.jpg) no-repeat center top; } li { list-style: none; } .baidu { overflow: hidden; margin: 100px auto; background-color: #fff; width: 410px; padding-top: 3px; } .baidu li { float: left; margin: 0 1px; cursor: pointer; } .baidu img { width: 100px; } </style> </head> <body> <ul class="baidu"> <li><img src="images/1.jpg"></li> <li><img src="images/2.jpg"></li> <li><img src="images/3.jpg"></li> <li><img src="images/4.jpg"></li> </ul> <script> var imgs = document.querySelector('.baidu').querySelectorAll('img') ; for ( var j = 0 ; j < imgs.length ; j++ ) { imgs[j].onclick = function () { // console.log(this.src); document.body.style.backgroundImage = 'url('+ this.src +')' ; } } </script> </body> </html>