2017-04-24 13 views
0

我基本上試圖用一個簡單的函數來更新元素的指定樣式屬性的值(不會弄亂或覆蓋其他樣式屬性)。例如,這個函數允許你輸入「top」作爲參數,並訪問/編輯element.style.top的值(或者相反,如果你輸入「left」,則element.style.left)。選擇具有簡單函數參數的元素的樣式屬性?

對於某些上下文,我的特定功能將允許用戶通過移動其邊緣位置(從而更改頂部,底部,左側或右側定位屬性)來調整元素的大小,以便指定的值動態響應用戶的輸入(因此不能由CSS類預先確定)。

一些可能性我認爲:

function changeStyleAttribute(el,attr) { //doesn't work (wrong syntax?) 
 
el.style.attr = new_value 
 
} 
 

 
function changeStyleAttribute(el,attr) { //doesn't work (wrong syntax?) 
 
el.setAttribute("style.attr",new_value) 
 
} 
 

 
function changeStyleAttribute(el,attr) { //could work but seems hack-y? 
 
el.setAttribute(attr,new_value) //overwrites all style attributes with property of interest 
 
el.classList.add(old_classes) //re-introduces all other default attributes of the element 
 

 
}

我覺得也許有我就是缺少一個更爲明瞭優雅的方式在本地JavaScript來做到這一點?

+2

嘗試'el.style [ATTR] = new_value' – Quantumplate

+0

謝謝,這是正是我需要的! Yay,學習基本語法:-) –

回答

0

如果該屬性的關鍵是動態值或變量,使用Square bracket notation

注意:您沒有設置屬性,但添加/修改CSS規則。

function changeStyleAttribute(el, cssRule) { 
    el.style[cssRule] = value; 
} 
+0

也許我誤解了你的評論,但以你和Quantumplate建議的方式訪問屬性似乎直接更新元素的樣式屬性(而不僅僅是CSS規則) –

+0

(除非你提到根據我自己的建議,向我的元素添加類,我現在可以從事後看到問題) –

相關問題