我基本上試圖用一個簡單的函數來更新元素的指定樣式屬性的值(不會弄亂或覆蓋其他樣式屬性)。例如,這個函數允許你輸入「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來做到這一點?
嘗試'el.style [ATTR] = new_value' – Quantumplate
謝謝,這是正是我需要的! Yay,學習基本語法:-) –