菜鸡源码,专注精品下载!
当前位置:首页 > 建站教程 > 建站知识

JavaScript中动态更改样式的方法

发布时间:2024-01-05  栏目:建站知识   浏览:   分类:js教程 JavaScript语法

JavaScript动态修改样式的方法主要有以下几种: 1. 通过`element.style`属性直接修改样式,例如`element.style.color = 'red';`。 2. 通过`element.className`属性修改类名,从而触发CSS中的类选择器,例如`element.className = 'active';`。 3. 使用`document.querySelector`或`document.getElementById`等方法获取元素,然后调用上述方法进行样式修改。 4. 使用`element.setAttribute('style', 'color: red;')`方法直接设置内联样式。

代码示例

<!DOCTYPEhtml><html><head><metacharset="UTF-8"><title>Title</title><style>*{margin:0;padding:0;list-style:none;}.lulli{height:90px;width:50px;}</style></head><body><button>3</button><button>4</button><button>5</button><div><ulstyle="position:relative"><listyle="background:red"></li><listyle="background:forestgreen"></li><listyle="background:yellow"></li><listyle="background:paleturquoise"></li><listyle="background:blue"></li><listyle="background:wheat"></li><listyle="background:darkturquoise"></li><listyle="background:rebeccapurple"></li><listyle="background:orange"></li><listyle="background:salmon"></li></ul></div><script>varlli=document.getElementsByClassName('lul')[0].children;console.log(lli);varbu3=document.getElementsByTagName('button')[0];varbu4=document.getElementsByTagName('button')[1];varbu5=document.getElementsByTagName('button')[2];bu3.onclick=function(){jiu(3);};bu4.onclick=function(){jiu(4);};bu5.onclick=function(){jiu(5);};functionjiu(row){//记录格子宽高,传递进来的是每行放几个livarheight=90,width=50;for(varx=0;x<lli.length;x++){//记录行与列varhang,lie;hang=parseInt(x/row);lie=x%row;console.log('第'+x+"个在第"+hang+"行"+lie+"列");//问题在这,每一个元素都要执行一遍这个赋值,是否可以直接在样式表中添加/*.lulli{height:90px;width:50px;position:absolute;}如上*/lli[x].style.position='absolute';lli[x].style.left=lie*width+'px';lli[x].style.top=hang*height+'px';}}</script></body></html>
相关专题
评论
建站知识
建站知识
使用技巧
调试安装
运营推广