DOM之设置,获取,删除自定义的属性值
1.设置自定义的属性以及属性值
element.setAttribute("属性名", "属性值");
自定义属性 规定以 data- 开头作为属性名
2.获取自定义的属性值
element.getAttribute("属性名");
3.删除自定义的属性名
element.removeAttribute("属性名")
代码示例
菜单栏切换
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 9 <style> 10 .box { 11 width: 350px; 12 height: 300px; 13 margin: 150px 300px 14 } 15 16 .box_title { 17 18 width: 320px; 19 height: 45px; 20 text-align: center; 21 line-height: 45px; 22 margin-left: 10px; 23 24 } 25 26 .box_title div { 27 28 float: left; 29 width: 100px; 30 border: 3px solid #999; 31 32 33 } 34 35 .current { 36 background-color: red; 37 font-size: 20px; 38 } 39 40 .box_content { 41 height: 150px; 42 width: 330px; 43 border: 5px solid#999; 44 45 } 46 47 .box_content div { 48 49 margin-top: 45px; 50 margin-left: 35px; 51 display: none; 52 color: blue; 53 } 54 55 </style> 56 </head> 57 58 <body> 59 <div class="box"> 60 <div class="box_title"> 61 <div class="current">早春</div> 62 <div>江南春</div> 63 <div>春游湖</div> 64 </div> 65 <br /> 66 <div class="box_content"> 67 <div style="display: block;">天街小雨润如酥,草色遥看近却无。<br /><br /> 68 最是一年春好处,绝胜烟柳满皇都。</div> 69 <div>千里莺啼绿映红,水村山郭酒旗风。<br /><br /> 70 南朝四百八十寺,多少楼台烟雨中。</div> 71 <div>双飞燕子几时回?夹岸桃花蘸水开。<br /><br /> 72 春雨断桥人不渡,小舟撑出柳阴来。</div> 73 </div> 74 </div> 75 76 77 78 <script> 79 var divs = document.querySelector('.box_title').querySelectorAll('div'); 80 81 var content_divs = document.querySelector('.box_content').querySelectorAll('div'); 82 83 for (var i = 0; i < divs.length; i++) { 84 85 //开始给每个div设置索引号,索引号从零开始 86 divs[i].setAttribute('data-index', i); 87 88 divs[i].onclick = function () { 89 //排它思想 90 for (var i = 0; i < divs.length; i++) { 91 divs[i].className = ''; 92 } 93 this.className = 'current'; 94 95 //获取上面的div 设置的索引号 96 var ide = this.getAttribute('data-index'); 97 98 99 100 for(var i=0;i<content_divs.length;i++){ 101 //排他思想 102 content_divs[i].style.display = 'none'; 103 } 104 content_divs[ide].style.display = 'block'; 105 } 106 107 108 109 110 } 111 </script> 112 </body> 113 114 </html>