sha*_*hay 1 html javascript css
嘿,我想从javascript更改一些CSS属性
但我无法访问该div的css值
这是我在我的css文件中的内容
#sidebar {
float: left;
width: 160px;
padding: 25px 10px 0 20px;
}
#sidebar ul {
margin: 0;
padding: 0;
list-style: none;
}
Run Code Online (Sandbox Code Playgroud)
这是我的div的html代码
<div id="sidebar">
<%@ include file="some_page.jsp" %>
</div>
Run Code Online (Sandbox Code Playgroud)
这是我的一些点击事件的javascript代码
var element = document.getElementById('sidebar');
alert(element.style.length); //Will alert 0
alert(element.style.width);//Empty alert box
Run Code Online (Sandbox Code Playgroud)
我想改变宽度属性,请你帮忙吗?
谢谢
试试这个代码的基础上,从这里代码: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';
}?
Run Code Online (Sandbox Code Playgroud)
编辑:
为了给出更可读的代码版本,这更接近于quirksmode版本.我改变了它以摆脱不必要的变量.
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;
}?
Run Code Online (Sandbox Code Playgroud)