css 中text

html-css014

css 中text,第1张

首行缩进(text-indent):{ text-indent: 24px}

文本对齐属性(text-align):

{ text-align: center}

{ text-align: left}

{ text-align: right}

文本修饰(text-decoration):

{ text-decoration: overline}

{ text-decoration: underline}

{ text-decoration: line-through}

{ text-decoration:none}

css中的text-indent用于设置首行缩进,用法如下。

需要准备的材料分别有:电脑、浏览器、html编辑器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html中的<style>标签中,输入css代码:body { text-indent: 50px}。

3、浏览器运行index.html页面,此时成功设置了首行缩进是50px大小。

给一个HTML元素设置css属性,如

复制代码

代码如下:

var

head=

document.getElementById("head")

head.style.width

=

"200px"

head.style.height

=

"70px"

head.style.display

=

"block"

这样写太罗嗦了,为了简单些写个工具函数,如

复制代码

代码如下:

function

setStyle(obj,css){

for(var

atr

in

css){

obj.style[atr]

=

css[atr]

}

}

var

head=

document.getElementById("head")

setStyle(head,{width:"200px",height:"70px",display:"block"})

发现

Google

API

中使用了cssText属性,后在各浏览器中测试都通过了。一行代码即可,实在很妙。如

复制代码

代码如下:

var

head=

document.getElementById("head")

head.style.cssText="width:200pxheight:70pxdisplay:bolck"

和innerHTML一样,cssText很快捷且所有浏览器都支持。此外当批量操作样式时,cssText只需一次reflow,提高了页面渲染性能。

但cssText也有个缺点,会覆盖之前的样式。如

复制代码

代码如下:

<div

style="color:red">TEST</div>

想给该div在添加个css属性width

复制代码

代码如下:

div.style.cssText

=

"width:200px"

这时虽然width应用上了,但之前的color被覆盖丢失了。因此使用cssText时应该采用叠加的方式以保留原有的样式。

复制代码

代码如下:

function

setStyle(el,

strCss){

var

sty

=

el.style

sty.cssText

=

sty.cssText

+

strCss

}

使用该方法在IE9/Firefox/Safari/Chrome/Opera中没什么问题,但由于

IE6/7/8中cssText返回值少了分号

会让你失望。

因此对IE6/7/8还需单独处理下,如果cssText返回值没""则补上

复制代码

代码如下:

function

setStyle(el,

strCss){

function

endsWith(str,

suffix)

{

var

l

=

str.length

-

suffix.length

return

l

>=

0

&&

str.indexOf(suffix,

l)

==

l

}

var

sty

=

el.style,

cssText

=

sty.cssText

if(!endsWith(cssText,

'')){

cssText

+=

''

}

sty.cssText

=

cssText

+

strCss

}

相关:

http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration

https://developer.mozilla.org/en/DOM/CSSStyleDeclaration