zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JS cssText属性的使用

JS属性 使用 cssText
2023-06-13 09:12:02 时间
在 JS属性操作的注意事项 一节中,例 2 使用 style 引用样式属性的方法来设置的样式是行内样式,这种方法一次只能设置单个样式,因此需要设置多个不同的行内样式时,要使用多条 JS 代码来分别设置,这就使得代码量相对比较多。

如果希望简化行内样式设置代码,我们可以使用 style 的 cssText 属性来同时设置多个样式,多个样式代码连写成一行代码,从而极大地减少了代码量。下面使用 cssText 属性来修改 JS属性操作的注意事项 中的例 2。

【例 1】使用 cssText 属性同时设置元素的多个行内样式。


 !doctype html 

 html 

 head 

 meta charset= utf-8 

 title 使用cssText属性同时设置元素的多个行内样式 /title 

 script 

 window.onload = function (){

 var oBtn1 = document.getElementById( btn1 

 var oBtn2 = document.getElementById( btn2 

 var oP = document.getElementById( p1 

 oBtn1.onclick = function(){

 //使用cssText属性后,只使用一行代码就同时设置了5个行内样式

 oP.style.cssText = width:300px;background:red;padding:20px;

 color:yellow;border:10px solid #ccc 

 oBtn2.onclick = function(){

 oP.style.cssText = width:330px;background:yellow;padding:10px;

 color:red;border:10px solid #333 

 /script 

 /head 

 body 

 input type= button id= btn1 value= 样式一 

 input type= button id= btn2 value= 样式二 

 p id= p1 12月3日午间消息,第四届世界互联网大会今日开幕,在全体大会上,腾讯公司控股董

 事会主席兼首席执行官马化腾发表了演讲,称未来互联网企业将给各行各业赋能,解决全部痛点。

 /body 

 /html 

上述代码在 Chrome 浏览器中的运行结果和例 2 完全一样。

cssText 属性不但可以添加元素的行内样式,也可以修改甚至清除元素的行内样式,示例如下。

【例 2】使用 cssText 属性添加、修改和清除元素行内样式。


 !doctype html 

 html 

 head 

 meta charset= utf-8 

 title 使用cssText属性设置元素行内样式 /title 

 style 

 div { width:100px;height:100px;border:1px solid red;}

 /style 

 script 

 window.onload = function (){

 var oDiv = document.getElementById( div1 

 var aBtn = document.getElementsByTagName( input 

 aBtn[0].onclick = function (){

 //添加行内样式

 oDiv.style.cssText = width:200px;height:120px;border:5px solid blue 

 aBtn[1].onclick = function (){

 //修改行内样式

 oDiv.style.cssText = width:150px;height:50px;border:2px dotted red 

 aBtn[2].onclick = function (){

 oDiv.style.cssText = //清除行内样式

 /script 

 /head 

 body 

 div id= div1 DIV /div 

 input id= btn1 type= button value= 添加行内样式 / 

 input id= btn2 type= button value= 修改行内样式 / 

 input id= btn3 type= button value= 清除行内样式 / 

 /body 

 /html 

上述代码首先使用内嵌样式给 div 元素设置了宽、高及边框样式。单击第一个按钮时会对 div 添加行内样式,我们看到添加的行内样式和内嵌样式存在冲突,由于行内样式的优先级高于内嵌样式,所以单击第一个按钮时,div 使用了行内样式。

在单击第一个按钮后再单击第二个按钮时,会用新的行内样式替换当前的行内样式。在添加或修改行内样式后,再单击第三个按钮时,会清除 div 的行内样式,此时,内嵌样式将发挥作用,即回到最初的样式。上述代码在 Chrome 浏览器中的运行结果如图 1~图 4 所示。

程序运行后的初始样式
图 1:程序运行后的初始样式 单击第一个按钮后的样式
图 2:单击第一个按钮后的样式 单击第二个按钮后的样式
图 3:单击第二个按钮后的样式 单击第三个按钮后的样式
图 4:单击第三个按钮后的样式

23973.html

CSShtml