![](/img/trans.png)
[英]Convert css styles to inline styles with javascript keeping the style units
[英]Create a div with inline styles from database .. want to set style with JavaScript?
我在數據庫中使用width,height,top和left屬性,以便將它們設置為特定的div。
$information =<<<HEREENDS
<div id = "randomDiv" style = "
left: {$array[0][3]}px;
top: {$array[0][4]}px;
width : {$array[0][5]}px;
height : {$array[0][6]}px; " >
</div>
HEREENDS;
echo $information;
那有效但是我正在尋找一個更智能的解決方案-有什么辦法可以將數組發送到javascript並使用javascript而不是內聯設置這些樣式?
先感謝您。
是。 JavaScript允許您通過style
屬性訪問和修改樣式值。 例如:
var myElement = document.getElementById("randomDiv");
myElement.style.left = $array[0][3] + 'px';
myElement.style.top = $array[0][4] + 'px';
myElement.style.width = $array[0][5] + 'px';
myElement.style.height = $array[0][6] + 'px';
或者,您可以使用style.cssText
將整個樣式字符串放入樣式中:
var myStyle = "left: {$array[0][3]}px;top:{$array[0][4]}px;width:{$array[0][5]}px;height : {$array[0][6]}px;";
document.getElementById("myElement").style.cssText = myStyle;
請注意, style.cssText
將覆蓋元素上的所有先前樣式。
如果該元素尚不存在,那么實際上沒有理由這樣做。 JavaScript仍然會簡單地修改元素的style
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.