div ,get css attributes from java script
hey there i want to change some css attributes from javascript
but i cant access css values for that div
here is what i have in my css file
#sidebar {
float: left;
width: 160px;
padding: 25px 10px 0 20px;
}
#sidebar ul {
margin: 0;
padding: 0;
list-style: none;
}
here is my html code for that div
<div id="sidebar">
<%@ include file="some_page.jsp" %>
</div>
here is my javascript code on some click event
var element = document.getElementById('sidebar');
alert(element.style.length); //Will alert 0
alert(element.style.width);//Empty alert box
i want to change the width attribute , can u help me please ?
thank you
Try this code, based on the code from here: http://www.quirksmode.org/dom/getstyles.html
var sidebarWidth = getStyle('sidebar','width');
function getStyle(el,styleProp) {
el = document.getElementById(el);
return (el.currentStyle)
? el.currentStyle[styleProp]
: (window.getComputedStyle)
? document.defaultView.getComputedStyle(el,null)
.getPropertyValue(styleProp)
: 'unknown';
}
EDIT:
To give perhaps a more readable version of the code, this is closer to the quirksmode version. I had changed it to get rid of the unnecessary variables.
var sidebarWidth = getStyle('sidebar','width');
function getStyle(el,styleProp) {
el = document.getElementById(el);
var result;
if(el.currentStyle) {
result = el.currentStyle[styleProp];
} else if (window.getComputedStyle) {
result = document.defaultView.getComputedStyle(el,null)
.getPropertyValue(styleProp);
} else {
result = 'unknown';
}
return result;
}
精彩评论