如何獲得元素的屬性
?我用下面的方法為什么不能獲得p3的屬性color,height,width??
function concel(){
???????? var p1=document.getElementById("p1");
???????? var p3=document.getElementById("p3");
???????? p1.style.color=p3.style.color.nodeValue;
???????? p1.style.width=p3.style.width.nodeValue;
???????? p1.style.height=p3.style.height.nodeValue;
???????? p1.style.display="block";
???? }
?
2016-12-14
直接使用style屬性無法訪問到內(nèi)嵌(寫在head標(biāo)簽中的),外部(寫在css文件中的)的css樣式,只能訪問內(nèi)聯(lián)樣式(寫在標(biāo)簽中的)的css樣式
2016-12-14
可能有兩個(gè)原因?qū)е履悴荒苷_取消設(shè)置屬性的問題,導(dǎo)致你懷疑可能是沒有獲取到屬性。
你代碼里面是否設(shè)置了唯一的id
你獲取到的屬性已經(jīng)被修改過,所以取消時(shí)再次賦值也取不到最初的值了。應(yīng)該要保存最初屬性。
貼一下驗(yàn)證通過的代碼,可以參考下:
var con=document.getElementById("con");
var txt=document.getElementById("txt");
var conColor=con.style.color;
var conHeight=con.style.height;
var conWidth=con.style.width;
var txtIsShow=con.style.display;
? ? function changeColor(){
? ? ? ? con.style.color="pink";
? ? }
//定義"改變寬高"的函數(shù)
? ? function changeWH(){
? ? ? ? con.style.height="500";
? ? ? ? con.style.width="300";
? ? }
//定義"隱藏內(nèi)容"的函數(shù)
? ? function hideTxt(){
? ? ? ? txt.style.display="none";
? ? }
//定義"顯示內(nèi)容"的函數(shù)
function showTxt(){
? ? txt.style.display="block";
}
//定義"取消設(shè)置"的函數(shù)
function cancel(){
? ? ?con.style.color=conColor;
? ? ? con.style.height=conHeight;
? ? ? ? con.style.width=conWidth;
? ? ? ? ? txt.style.display=txtIsShow;
}