【问题标题】:jQuery and Setting CSS with ShorthandjQuery 和使用简写设置 CSS
【发布时间】:2012-02-26 12:00:10
【问题描述】:

来自:专业 PHP 和 jQuery:

■ 提示返回的值是 CSS 速记属性。3 添加了一个 jQuery 的好处是能够使用 CSS 设置 CSS 属性 速记,不能使用基本的 JavaScript。

来自 jQuery API 参考:

简写 CSS 属性(例如边距、背景、边框)不是 支持的。例如,如果要检索渲染的边距, 使用:$(elem).css('marginTop') 和 $(elem).css('marginRight'),等等 开。

我一头雾水,css简写可以设置,但不能读取?当然我会简单地使用样式表,但是,问题是为了学术教育。

【问题讨论】:

  • 没错。即使您可以使用 CSS 速记设置属性,浏览器仍然会将这些属性分解为各自的部分(这是计算样式)。元素在浏览器中没有 'margin' 属性,它们将具有 'margin-top'、'margin-right'、'margin-bottom'、'margin-left'。

标签: jquery css


【解决方案1】:

如果您使用的是 firefox 或 chrome,请打开控制台。输入这个:

jQuery(".post-text"); // will select the post of this answer, you should see it in the console
jQuery(".post-text").css("margin"); // will be "", the shorthand returns NOTHING
jQuery(".post-text").css("margin-top"); // will be "0px", the real notation works
jQuery(".post-text").css("margin","10px 10px 10px 10px"); // we just set all margins with shorthand, you should notice a change in the UI of stackoverflow.
jQuery(".post-text").css("margin-top"); // is "10px" now
jQuery(".post-text").css("margin"); // is still ""

我希望这能澄清这个概念。简短回答:您可以设置,但不能获得速记 css 属性。

【讨论】:

    【解决方案2】:

    使用 getter 方法 .css(propertyName) 方法获取 jquery css 速记时不起作用。

    您可以使用 css 简写来定义 css 规则:

    $('div').css("border", "2px solid Black");
    

    DEMO

    【讨论】:

      【解决方案3】:

      您可以设置速记 CSS 属性,因为它们被应用并解释为单独的样式。

      但是,除非特别编程,否则无法完成相反的过程。

      例如,您可以对阅读器进行编程以检测margin 之类的速记属性并返回串联的margin-topmargin-rightmargin-bottommargin-left

      也就是说,速记有多种可能性。例如,margin: 10px 20px 仍然设置所有四个边距,但检索它可能会产生 10px 20px 10px 20px,这与输入的不同。

      基本上,长话短说,速记属性转换为一组单独的属性,但一组单独的属性可能会导致几种可能的速记。

      【讨论】:

        猜你喜欢
        • 2015-11-25
        • 2014-09-01
        • 2018-03-20
        • 1970-01-01
        • 2013-08-02
        • 2015-06-30
        • 2014-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多