我正在尝试获取 CSS 属性的名称和值并将它们写入页面。问题是这些值不会实时改变,例如不透明度应显示从 1 到 0 的递减值。填充、边框和边距值也未显示。这可以通过在 firefox 中打开页面并使用 firebug 检查它来看到。
标记
<div id="container">
<div id="box">click to hide me</div>
<p id="result"> </p>
</div>
风格
#container {
overflow: auto;
}
#box {
width: 400px;
height: 400px;
padding: 10px;
border: 5px solid black;
margin: 15px;
background-color: red;
text-align: center;
float: left;
}
#result {
width: 400px;
height: 200px;
border: 1px solid #CCCCCC;
background-color: #EEE;
float: right;
margin-right: 20px;
}
脚本
$(document).ready(function() {
$( "#box" ).click(function() {
var html = [ "The clicked div has the following styles:" ];
var styleProps = $( this ).css(["width", "height", "padding", "border", "margin", "opacity", "display"]);
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});
$( "#result" ).html( html.join( "<br>" ) );
});
$("#box").click(function() {
$("#box").hide(5000);
});
});
需要说明的是,我是 jQuery/javascript 的菜鸟,我正试图找出 jQuery hide() 方法更改了哪些值和哪些值。在 firefox 中使用 firebug,我看到高度、宽度、边框、填充、边距、不透明度和显示都为空。我试图在页面本身的结果 div 中显示这一点。
最佳答案
这里有几个问题。
- 您不能一次获得
margin
、padding
和border
css 属性。您需要获取诸如marginTop
、paddingBottom
、borderWidth
等内容。 您需要为单独的函数获取状态更新,然后在隐藏的
progress
上调用它。$.fn.update = function(element) { var html = [ "The clicked div has the following styles:" ]; var styleProps = $( this ).css(["width", "height", "opacity", "display"]); $.each( styleProps, function( prop, value ) { html.push( prop + ": " + value ); }); element.html(html.join("<br>")); } var box = $("#box"); box.click(function() { box.hide({ duration: 5000, progress: function() { box.update($("#result")); } }); });
关于javascript - 使用 jQuery 获取 CSS 属性并写入页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22091401/