javascript - 使用 jQuery 获取 CSS 属性并写入页面

标签 javascript jquery html css

我正在尝试获取 CSS 属性的名称和值并将它们写入页面。问题是这些值不会实时改变,例如不透明度应显示从 1 到 0 的递减值。填充、边框和边距值也未显示。这可以通过在 firefox 中打开页面并使用 firebug 检查它来看到。

标记

<div id="container">
    <div id="box">click to hide me</div>
    <p id="result">&nbsp;</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 中显示这一点。

fiddle

最佳答案

这里有几个问题。

  1. 您不能一次获得 marginpaddingborder css 属性。您需要获取诸如 marginToppaddingBottomborderWidth 等内容。
  2. 您需要为单独的函数获取状态更新,然后在隐藏的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"));
            }
        });
    });
    

Fiddle for ya

关于javascript - 使用 jQuery 获取 CSS 属性并写入页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22091401/

相关文章:

javascript - 当 JSON 对象为空时显示适当的消息

javascript - JQuery 将文本设置为输入文本字段

html - CSS 宽度 :100% textarea for comment (responsive)

javascript - Backbone js。如何在backbone js中将数据从 View 传递到模板

javascript - 将带有文件输入的多个图像上传到 Canvas 元素

javascript - 从 <object> 节点获取 SVG 根元素及其子元素以导出具有动态内容的 SVG

javascript - 为什么 `splice.apply(arguments, 0)` 失败而 `splice.call(arguments, 0)` 返回数组

javascript - 当输入类型 ="date"的日期明确作为第一个操作时,onchange 不会触发

javascript - Jquery 下拉导航

javascript - jQuery/JS 不会在验证表单后重定向