将元素显示无返回到默认样式值JS [英] Change element display none back to default style value JS

查看:73
本文介绍了将元素显示无返回到默认样式值JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何创建一个将元素恢复为默认样式值的函数。例如,对于一个图像是inline-> , c> 块,其他元素inline或列表list-item如何恢复其默认状态?

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

我知道如何在Jquery中做,



在CSS中,可能有包含 style:none



由于在我的示例中有CSS style.display =''消除了添加JS的样式,但可以返回CSS中添加的任何样式,即使在使用CSS分配样式之前,我仍希望将其恢复为默认值。



尝试这是因为它是在其中一个注释的链接中建议:

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

但在本例中'theCSSprop' none对于 div ,当我期望block



任何想法?
感谢。

解决方案

您只需将其分配为空值:

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

或使用 removeProperty 方法:

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

但请注意, removeProperty IE< 9



如果你想得到原始的CSS值,你需要从空的< iframe> 元素。我在jsFiddle上创建了示例,如何使用 getComputedStyle

请注意, getComputedStyle 不支持旧版IE。它支持IE9 +。



对于IE8,您应该使用 Element.currentStyle


I have a function in JS that hides the element parsed:

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

How can I create a function that brings back the element to the default style value. For instance a div display property is "block" as for an image is "inline-block", other elements are "inline" or lists are "list-item" How can I bring them back their default state?

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

I know how to do it in Jquery but it is not an option.

In CSS there might be styles for the elements including style:none, which need to be overwritten to the default value.

Since there is CSS in my example making style.display = '' eliminates the style added with JS but gets back to whatever style is added in CSS, I want to bring it back to its default value even before assigning styles with CSS.

I tried this as it was suggested in a link in one of the comments:

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

but in this case 'theCSSprop' returns "none" for a div, when I expect "block"

Any ideas? Thanks.

解决方案

You need just assign it to empty value:

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

Or using removeProperty method:

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

But note that removeProperty will not work on IE<9.

If you want to get original CSS value you will need probably to get it from empty <iframe> element. I created example on jsFiddle how to get current value using getComputedStyle and iframe value on jsFiddle.

Please note that getComputedStyle not support old versions of IE. It support IE9+.

For IE8 you should use Element.currentStyle

这篇关于将元素显示无返回到默认样式值JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆