javascript怎么修改元素
程序员文章站
2022-03-07 13:20:42
...
方法:1、使用“element.innerText='值'”或“element.innerHTML='值'”语句修改元素内容;2、使用“element.style”或“element.className”语句修改元素样式属性。
本教程操作环境: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>
运行后,显示某个时间,当点击显示系统当前时间即可显示进当前的日期及星期。
修改样式属性
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>
【相关推荐:javascript学习教程】
以上就是javascript怎么修改元素的详细内容,更多请关注其它相关文章!
上一篇: 在WPF程序中使用多线程技术
下一篇: javascript中区分大小写吗
推荐阅读
-
javascript - jQuery给动态添加的元素绑定事件的问题?
-
毫无排版和缩进的 JavaScript 代码,怎么阅读?
-
javascript - 正则贪婪模式,怎么搞清楚?总是一下子把后面的都给匹配上了
-
javascript - 用户发帖应用开发中,用户异步上传了图片,但最终帖子没发布,那么上传的图不就没有用了吗怎么处理这种情况?
-
js中设置元素class的三种方法小结_javascript技巧
-
遍历DOM对象内的元素属性示例代码_javascript技巧
-
javascript pop() 删除数组中最后的一个元素
-
javascript抖动元素的小例子_javascript技巧
-
怎么修改一个部署集的名称和描述信息
-
javascript - 怎么实现微软edge浏览器兼容性提示?