元素获取与属性获取
getElementById
*{margin: 0;padding: 0}
#wrap{width: 300px;margin: 20px auto;}
#wrap li{float: left;list-style: none;margin: 5px;}
#wrap li a{text-decoration: none;lighting-color: }
#list{position: absolute;border: 1px solid #999;left: -22px;display: none;}
#list li{width: 70px;height: 25px;line-height: 25px;text-align: center;}
<ul id="wrap">
<li><a href="#">新闻</a></li>
<li><a href="#">地图</a></li>
<li><a href="#">贴吧</a></li>
<li id="setting" style="position: relative;">
<a href="#">设置</a>
<ul id="list">
<li>搜索设置</li>
<li>高级搜索</li>
<li>关闭预测</li>
<li>搜索历史</li>
</ul>
</li>
</ul>
document.getElementById('setting').onmouseover = show;
document.getElementById('setting').onmouseout = hide;
function show(){
document.getElementById('list').style.display = 'block';
}
function hide(){
document.getElementById('list').style.display = 'none';
}
getElementsByTagName
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
window.onload = function(){
var oUl = document.getElementById('list');
var lis = oUl.getElementsByTagName('li');
alert(Array.isArray(lis));
for(var i=0;i<lis.length;i++){
lis[i].index = i;
lis[i].onclick = function(){
alert(this.index);
}
}
}
属性的获取
<input type="text" value="潭州学院" id="input1" class="inp" yw="很帅" style="margin-left: 30px;">
<input type="button" value="按钮" id="btn1">
window.onload = function(){
var oInp = document.getElementById('input1');
var oBtn = document.getElementById('btn1');
oBtn.onclick = function(){
alert(oInp.style.marginLeft);
}
}
属性值设置
<input type="text" value="潭州学院" id="text">
<input type="button" value="按钮" id="btn">
<div id="wrap"></div>
var oText = document.getElementById('text');
var oBtn = document.getElementById('btn');
var oWrap = document.getElementById('wrap');
var flag = true;
oWrap.style.background = 'yellow';
oWrap.style.border = '1px solid red';
oWrap.style.width = '100px';
oWrap.style.height = '100px';
oBtn.onclick = function(){
var attr;
if(flag){
attr = 'width';
}else{
attr = 'height';
}
oWrap.style[attr] = '200px';
for(var key in oWrap){
console.log(key, '====', oWrap[key]);
}
}
图片的相对路径问题与background问题
<img src="1.jpg" width="200" height="200" id="img">
<div id="box" style="background: #000;width: 100px;height: 100px;"></div>
<input type="button" id="btn" value="按钮">
var oImg = document.getElementById('img');
var oBtn = document.getElementById('btn');
var oBox = document.getElementById('box');
if(oImg.src=='1.jpg'){
alert('不帅');
}else{
alert('很帅');
}
document.write(oImg.src);
if(oImg.src=='http://www.yw.nodejs.com:88/js01/1.jpg'){
alert('很帅');
}else{
alert('不帅');
}
alert(oBox.style.background);
if(oBox.style.background=='#000'){
alert('不帅');
}else{
alert('太帅了');
}