html代碼中id="img_list" 是需要動態添加的容器,id="append"里面是靜態元素,動態元素和靜態元素通用css樣式。其問題主要出在動態的所有 class="zhezhao"的節點樣式(鼠標滑過時透明度變化)。問題1:如何讓動態元素?class="zhezhao"部分顯示正確的樣式?問題2:靜態css樣式大部分在動態元素上顯示正常,但這樣應用是否合理?就是說靜態元素應用靜態樣式,動態元素應用動態樣式為合理?html代碼如下:<div?id="img_list">
</div>
<div?id="hrs"><hr/></div>
<div?id="append">
????<div?id="cont">
????????<div?id="div1">
????????????<img?src="img/5vip.jpg"/>
????????????<div>第一VIP</div>
????????</div>
????????<div?id="text">示例1</div>
????????<div?id="zhezhao"?class="zhezhao"></div>
??????</div>
????<div?id="cont">
????????<div?id="div1">
??????????????<img?src="img/5vip.jpg"/>
??????????????<div>第一VIP</div>
????????</div>
????????<div?id="zhezhao"?class="zhezhao"></div>
????</div>
</div>css部分:img{
????width:?250px;
????height:?150px;
}
#cont{
????background-color:?#A9A9A9;
????text-align:?center;
????overflow:?hidden;
????float:?left;
????margin:?3px;
????position:?relative;
}
#div1{
????border:?1px?solid?#FF0000;
????float:?left;
????background-color:?#FAEBD7;
}
#text{
????width:?110px;
????position:?absolute;
????background-color:?#FFA500;
????transform:?rotate(-45deg)?translate(-30px,-5px);
????-webkit-transform:?rotate(-45deg)?translate(-30px,-5px);
????font-size:?16px;
????padding:?3px?3px;
}
#hrs{
????clear:?both;
}
.zhezhao{
????background-color:?#0000CC;
????width:?100%;
????height:?100%;
????position:?absolute;
????opacity:?0.1;
}
.zhezhao:hover{
????opacity:0.5;
}動態添加元素的js部分:function?$(id){
????return?document.getElementById(id);
}
window.onload=function(){
????var?objarr=[];
????//動態添加初始化
????inints();
????function?inints(){
????????$("img_list").innerHTML=sethtml();?
????????//以下貌似不獨立設置,應用靜態css大部分也可以???
????????//setstyle();
????}
????function?sethtml(){
????????var?ss="";
????????var?str="";
????????for?(var?i=0;i<3;i++)?{
????????????var?info=new?Object
????????????var?id="zhezhao-"+(i+1);?
????????????if(i==0){
????????????????ss="<div?id='text'>示例"+(i+1)
????????????}else{
????????????????ss="";
????????????}?
????????????str+="<div?id='cont'><div?id='div1'><img?src='img/5vip.jpg'/><div>第"
????????????+(i+1)+"VIP</div></div>"+ss+"</div><div?id='"+id+"'?class='zhezhao'?name='zz'></div></div>"?
????????}
????????console.log(str);?
????????return?str;
????}
????function?setstyle(){
????????var?aa=document.getElementsByName("zz")
????????for(var?i=0;i<aa.length;i++){
????????????aa[i].style.cssText="background-color:?#0000CC;width:?100%;height:?100%;position:?absolute;opacity:?0.1;"
????????}
????}
}
JS動態添加元素和設置其樣式問題
azureks
2016-07-03 15:49:03