【问题标题】:Change element display none back to default style value JS将元素显示无更改为默认样式值 JS
【发布时间】:2014-02-22 20:08:38
【问题描述】:

我在 JS 中有一个函数可以隐藏解析的元素:

function hide(id){
  document.getElementById(id).style.display = "none";
}

如何创建将元素恢复为默认样式值的函数。例如 div display 属性是 "block" 图像是 "inline-block",其他元素是 "inline" 或列表是 "list-item" 我怎样才能将它们恢复到默认状态?

function show(id){
  document.getElementById(id).style.display = "?????";
}

我知道如何在 Jquery 中做到这一点,但这不是一个选项。

在 CSS 中可能有包括style:none 在内的元素的样式,需要将其覆盖为默认值。

由于在我的示例中有 CSS,使 style.display = '' 消除了使用 JS 添加的样式,但恢复了添加到 CSS 中的任何样式,因此我想在使用 CSS 分配样式之前将其恢复为默认值。

我按照其中一个 cmets 的链接中的建议进行了尝试:

elem = document.getElementById(id);
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("display");

但在这种情况下,'theCSSprop' 返回"none"div,而我期望"block"

有什么想法吗? 谢谢。

【问题讨论】:

标签: javascript html css


【解决方案1】:

您只需将其分配给空值:

document.getElementById(id).style.display = "";

或者使用removeProperty方法:

document.getElementById(id).style.removeProperty( 'display' );

但请注意,removeProperty 不适用于 IE<9

如果您想获得原始 CSS 值,您可能需要从空的 <iframe> 元素中获取它。我在 jsFiddle 上创建了 example 如何使用 getComputedStyle 和 jsFiddle 上的 iframe 值获取当前值。

请注意getComputedStyle 不支持旧版本的 IE。支持IE9+。

对于 IE8 你应该使用Element.currentStyle

【讨论】:

  • 这很好用,因为它只是从内联样式中删除了 display 属性,因此显示返回到它在 css 中定义的内容
  • 谢谢,我明白你的意思并且它有效,除了在 css 中我可能有 display:none;所以通过 style.display = "";它从 CSS 样式表中取回样式,而不是元素的默认值。我也改变了我的问题。谢谢!
  • @antyrat,谢谢。正如我之前提到的,如果 CSS 样式表中没有修改默认样式,则您的答案解决了问题,我尝试了您共享的链接并返回“null”,看看我的答案,您能提供一个工作示例吗?非常感谢。
  • iframe 的绝佳解决方案。 +1
【解决方案2】:

注意: 如果您为类或标记定义 display:none;(在单独的 css 文件中或在 head 部分中),上述方法将不起作用。

然后你必须确定它是哪种类型的标签+类并手动分配特定于它的值。


这些是可能不起作用的示例:

// In many cases this won't work:
function ShowHide_WillRarelyWork(id, bDisplay) {
    // Note: This will fail if parent is of other tag than element.
    var o = document.getElementById(id);
    if (o == null) return;
    //
    if (bDisplay) {
        o.style.display = 'inherit';
        o.style.visibility = true;
    }
    else {
        o.style.display = 'none';
    }
} // ShowHide_WillRarelyWork(...)

// This will work in most, but not all, cases:
function ShowHide_MayWork(id, bDisplay) {
    // Note: This will fail if element is declared as 'none' in css.
    var o = document.getElementById(id);
    if (o == null) return;
    //
    if (bDisplay) {
        o.style.display = null;
        o.style.visibility = true;
    }
    else {
        o.style.display = 'none';
    }
} // ShowHide_MayWork(...)

这很长,但很可能会起作用:

function getDefaultDisplayByTag(sTag) {
    // This is not fully implemented, as that would be very long...
    // See http://www.w3.org/TR/CSS21/sample.html for full list.
    switch (sTag) {
        case 'div':
        case 'ul':
        case 'h1':
        case 'h2':
        case 'h3':
        case 'h4':
        case 'h5':
        case 'h6':      return 'block';
        //
        case 'li':      return 'list-item';
        //
        case 'table':   return 'table';
        //
        case 'td':
        case 'th':      return 'table-cell';
    }
    // Fallback:
    return 'block';
} // getDefaultDisplayByTag(...)
//
function computeDisplay(o) {
    var oFunction = window.getComputedStyle;
    if (oFunction) {
        var oStyle = window.getComputedStyle(o)
        if ((oStyle) && (oStyle.getPropertyValue)) {
            return oStyle.getPropertyValue('display');
        }
    }
    if (window.currentStyle) {
        return window.currentStyle.display;
    }
    return null; // <-- This is going to be a bad day...
} // computeStyle(...)
//
// This will most probably work:
function ShowHideObject_WillProbablyWork(o, bDisplay, bMaybeRecursive) {
    if ((o == null) || (o == undefined) || (o == document) || (o.tagName == undefined)) return;
    //
    if (bDisplay == null) bDisplay = true
    if (!bDisplay) {
        o.style.display = 'none';
    }
    else {
        // First remove any directly set display:none;
        if ((o.style.display == 'none') || (o.style.display == '')) {
            o.style.display = null;
        }
        //
        var sDisplay = null;
        var sDisplayCurrent = computeDisplay(o);
        var oParent = o.parentNode;
        // Was this element hidden via css?
        if ((sDisplayCurrent == null) || (sDisplayCurrent == 'none')) {
            // We must determing a sensible display value:
            var sTag = o.tagName;
            sDisplay = getDefaultDisplayByTag(sTag);
        } // else: if ((sDisplayCurrent != null) && (sDisplayCurrent != 'none'))
        //
        // Make sure visibility is also on:
        if (sDisplay != null) o.style.display = sDisplay;
        o.style.visibility = true;
        //
        if (bMaybeRecursive) {
            // We should travel up the tree and make sure parent are also displayed:
            ShowHideObject_WillProbablyWork(oParent, true, true);
        }
    } // else: if (!bDisplay) ...
    //
} // ShowHideObject_WillProbablyWork(...)
//
// ... and finally:
function ShowHideId_WillProbablyWork(id, bDisplay, bMaybeRecursive)
    var o = document.getElementById(id);
    ShowHideObject_WillProbablyWork(o, bDisplay, bMaybeRecursive)
} // ShowHideId_WillProbablyWork(...)

当然这可以缩短一点;但这就是它在我的源代码中的样子。

【讨论】:

    【解决方案3】:

    这是检索任何元素的任何属性默认值的另一种解决方案。思路如下:

    1. 获取特定元素的nodeName
    2. 在正文中附加一个具有相同节点名称的假元素
    3. 获取假元素的任意属性值。
    4. 移除虚假元素。

    function getDefaultValue(element, property) {
        var elDefault = document.createElement(element.nodeName);
        document.body.appendChild(elDefault);
        propertyValue = window.getComputedStyle(elDefault,null).getPropertyValue(property);
        document.body.removeChild(elDefault);
      return propertyValue;
    }
     function resetPropertyValue (element,propertyName) {
        var propertyDefaultValue = getDefaultValue(element, propertyName);
        if (element.style.setProperty) {
            element.style.setProperty (propertyName, propertyDefaultValue, null);
        } 
        else {
            element.style.setAttribute (propertyName, propertyDefaultValue);
        }
    }
    #d {
      background: teal;
      display: inline;
    }
    <button onclick="resetPropertyValue(document.getElementById('d'), 'display')">Try it</button>
    <div id="d">test</div>

    【讨论】:

      【解决方案4】:

      您可以使用自定义属性

      function hide(id){
          var elem = document.getElementById(id);
          //Store prev value
          elem.setAttribute('custom-attr', elem.style.display);
          elem.style.display = "none";
      }
      
      function show(id){
          var elem = document.getElementById(id);
          //Set prev value
          elem.style.display = elem.getAttribute('custom-attr');
      }
      

      【讨论】:

      • 我建议使用数据属性,这是一个适用于此类情况的有效属性。因此,不要使用“custom-attr”,而只需使用“data-olddisplay”或类似的东西。
      • 如果你调用 hide 两次,并且元素初始化为隐藏,这不起作用,因为你没有 attr
      【解决方案5】:

      填充空值会移除内联覆盖,因此原始值再次处于活动状态。

      function show(id){
          document.getElementById(id).style.display = "";
      }
      

      【讨论】:

      • 如果在
      【解决方案6】:

      由于您想要的是元素的默认值而不是样式表中的默认值,因此您只需将该值设置为 auto。

      document.getElementById(id).style.display="auto"
      

      这告诉浏览器计算这种类型元素的正常显示是什么并使用它。

      【讨论】:

      • auto 不是 display 的有效值。也许你的意思是initial
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 2020-05-21
      • 2023-03-30
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多