Rumah > Soal Jawab > teks badan
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.bgcolor{background: #ccc;}
.bgcolor1{background: red;}
#p1 #text .text1{width: 730px;height: 80px;fiter:alpha(opacity=100);opacity: 1;display: block;}
#p1 #text .text2{width: 730px;height: 80px;fiter:alpha(opacity=100);opacity: 0;display: none;}
#p1 #text .text3{width: 730px;height: 80px;fiter:alpha(opacity=100);opacity: 0;display: none;}
#p1 #btn a{width: 16px;height: 16px;border-radius: 50px;display:inline-block;margin-left: 10px;}
#p1 #btn li{list-style: none;float: left;}
</style>
</head>
<body>
<p id="p1">
<p id="text" class="">
<p class="text1">111111111<br/>1111111111111111111111111111<br/>
1111111111111111111111111111111</p>
<p class="text2">222222222222222222222<br/>2222222222222222222222222<br/>222222222222</p>
<p class="text3">3333333333<br/>333333333333333333333333333</p>
</p>
<p id="btn" class="">
<ul>
<li><a href="javascript:;" class="bgcolor1"></a></li>
<li><a href="javascript:;" class="bgcolor"></a></li>
<li><a href="javascript:;" class="bgcolor"></a></li>
</ul>
</p>
</p>
<script>
window.onload=function(){
var op=document.getElementById('p1');
var oTxt=op.getElementsByTagName('p');
var oBtn=document.getElementsByTagName('a');
var alpha=0;
var timer=null;
for(var i=0;i<oBtn.length;i++){
oBtn[i].index=i;
oBtn[i].onclick=function(){
for(var i=0;i<oBtn.length;i++){
oBtn[i].className='bgcolor';
oTxt[i].style.display='none';
}
this.className='bgcolor1';
//otxt[this.index].style.display='block';
oTxt[this.index].style.display='block';
startMove()
}
}
function startMove(){
var op=document.getElementById('p1');
var oTxt=op.getElementsByTagName('p');
clearInterval(timer);
timer=setInterval(function(){
if(alpha==100){
clearInterval(timer);
}
else{
alpha=alpha+10;
oTxt[this.index].style.opacity=alpha/10;
}
},30);
}
}
</script>
</body>
</html>
具体是这样,我想通过点击按钮来更改字段的显示。例如这样
然后想让点击时,让
字段的opacity透明度从0到1来个过渡,于是我放了一个定时器
但是报错了,并无法出现想要的透明过渡效果。
错误:Uncaught TypeError: Cannot read property 'style' of undefined
但是如果不调用定时器的函数,直接给值却是可以显示的。
oTxt[this.index].style.display='block';
//startMove()
oTxt[this.index].style.opacity=100;
错在哪里了呢?
PHP中文网2017-04-10 17:04:02
原因就是this
的指向问题,但是我这么更改后你就不会报错了,this
的指向的具体情况,百度一下会有很多答案(只有4种情况),你的这个原因就是this
指向了全局对象window
,而不是你所点击的那个按钮。另外如果你是想要淡入淡出效果的话,你的startMove
代码还是有一些问题的。对你代码做了以下的更改,但是更改后代码不兼容低版本ie的兼容。
// 切换按钮处更改
oBtn[i].onclick=function(){
for(var i=0;i<oBtn.length;i++){
oBtn[i].className='bgcolor';
oTxt[i].style.display='none';
oTxt[i].style.opacity = 0;
}
this.className='bgcolor1';
oTxt[this.index].style.display='block';
startMove(this);
}
// startMove函数更改
function startMove(_this){
var op=document.getElementById('p1');
var oTxt=op.getElementsByTagName('p');
clearInterval(timer);
timer = setInterval(function(){
var alpha = +oTxt[_this.index].style.opacity;
if (alpha === 1) {
clearInterval(timer);
}
else{
alpha += 0.1;
oTxt[_this.index].style.opacity = alpha;
}
},30);
}