站长资讯网
最全最丰富的资讯网站

javascript怎么修改元素

方法:1、使用“element.innerText='值'”或“element.innerHTML='值'”语句修改元素内容;2、使用“element.style”或“element.className”语句修改元素样式属性。

javascript怎么修改元素

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

操作修改元素


JavaScript的DOM操作可以改变网页内容、结构和样式,我们可以利用DOM操作元素来改变元素里面的内容、属性等。

改变元素的内容

element.innerText从起始位置到终止位置的内容,但它去除html标签,同时空格和换行也会去掉

element.innerHTML起始位置到终止位置的全部内容,包括html标签,同时保留空格和换行。

innerText不识别HTML标签,innerHTML识别HTML标签。这两个属性是可读写的。

<body>     <button>         显示系统当前时间     </button>     <div>         某个时间     </div>     <script>     	var btn = document.querySelector('button');         var div = document.querySelector('div');         btn.onclick = function(){             div.innerText = getDate();         }                  function getDate(){             var date = new Date();             var year = date.getFullYear();             var month = date.getMonth()+1;             var dates = date.getDate();             var arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];             var day = date.getDay();             return '今天是'+year+'年'+month+'月'+dates+'日'+arr[day];         }     </script> </body>

javascript怎么修改元素

运行后,显示某个时间,当点击显示系统当前时间即可显示进当前的日期及星期。

javascript怎么修改元素

修改样式属性

element.style修改行内式操作,element.className修改类名样式属性

<head> 	<style>         div {             width:200px;             height:200px;             background-color:pink;         } 	</style> </head> <body>     <div>              </div>     <script>     	var div = document.quertSelector('div');         div.onclick = function(){          this.style.backgroundColor = 'purple';          this.style.width='300px';         }      </script> </body>

程序运行后,出现一个宽高均为200像素的粉红色盒子,点击盒子,变成宽300像素高200像素的紫色盒子。JS修改style样式操作,产生的是行内样式。

使用className更改样式属性

<head>     <style>         div {             width:100px;             height:100px;             background-color:pink;         }         .change {             width:200px;             height:200px;             background-color:purple;         }     </style> </head> <body>     <div>        文本         </div>     <script>     	vet test =document.querySelector('div');         test.onclick = function(){             //将当前元素的类名改为change           this.className = 'change';           }     </script>      </body>

赞(0)
分享到: 更多 (0)
网站地图   沪ICP备18035694号-2    沪公网安备31011702889846号