控制样式
元素.style.css属性名='css属性值'
在css属性用-连接的属性,在JS中要转换成驼峰命名
box.style.background='#f00'
box.style.width='500px'
box.style.height='300px'
box.style.color='#00f'
bar.style.display="none"
修改className
要修改html元素的class属性,需要使用className
<head>
<style>
div{width:200px;height:200px;background:#333;}
div.red{background-color:#f00;width:400px;height:300px;color:#fff;}
</style>
</head>
<body>
<button id="red">红色</button>
<div id="box">hello</div>
<script>
var red=document.getElementById('red')
var box=document.getElementById('box')
red.onclick=function(){box.className='red'}
</script>
</body>
属性
- 获取标准属性值
元素.属性名
alert(box.className)
alert(box.id)
- 设置标准属性的值
元素.属性名 = “属性值”
<button id="red">红色</button>
<img id="box" src="图片1.jpg">
<script>
var box=document.getElementById('box')
var red=document.getElementById('red')
red.onclick=function(){
box.src="图片2.jpg"
}
</script>
innerText&textContent
获取元素文本内容, innerText是IE率先支持,但不在标准里,没有兼容问题
textContent 是标准写法,但是不兼容IE8
<div id="box">Hello JavaScript!</div>
<script>
var box=document.getElementById('box')
alert(box.innerText)
alert(box.textContent)
</script>
设置内容值的时候,标签会被当作文本
box.innerText='<h1>你好</h1>'
innerHTML
获取元素中完整HTML内容,包含文本内容及标签
alert(box.innerHTML)
box.innerHTML='<h1>你好</h1>'
value
获取控件类元素的值
<body>
<input id="ipt" type="text">
<select id="slt">
<option value="篮球">篮球</option>
<option value="足球">足球</option>
<option value="排球">排球</option>
</select>
<button id="btn">获取</button>
<script>
var ipt=document.getElementById('ipt')
var btn=document.getElementById('btn')
var slt=document.getElementById('slt')
btn.onclick=function(){
alert(slt.value)
ipt.value='你好'
}
</script>
</body>
字符串拼接
<script>
var str='gx'
alert('hello'+str)
</script>