javascript - Div 样式未定义(Javascript)

标签 javascript html styles

我在 stackoverflow 中找到了这个脚本。

 function showhide(id){
        if (document.getElementById) {
          var divid = document.getElementById(id);
          var divs = document.getElementsByClassName("hideable");
          for(var div in divs) {
             div.style.display = "none";
          }
          divid.style.display = "block";
        } 
        return false;
       }

<a href="#" onclick="showhide('features');" >features</a>
<a href="#" onclick="showhide('design');"  >design</a>
<a href="#" onclick="showhide('create');" >create</a>

<div class="hideable" id="features">Div 1</div>
<div class="hideable" id="design">Div 2</div>
<div class="hideable" id="create">Div 3</div>

但是它说,div.style undefined。为什么? :)

最佳答案

你不应该为此使用 for-in 循环。

document.getElementsByClassName('someClass')

返回 NodeList ,它不继承自 Array.prototype,但在某些方面是相似的。顾名思义,它是一个节点列表。这意味着它有一个 length 属性,只能使用以下方式访问:

var myElements = document.getElementsByClassName('yourClass');
for (var i = 0, ii = myElements.length; i < ii; i++) {
    console.dir(myElements[i].style);
};

下面是隐藏元素的实际方式。

/**
 * Shows or hides an element from the page. Hiding the element is done by
 * setting the display property to "none", removing the element from the
 * rendering hierarchy so it takes up no space. To show the element, the default
 * inherited display property is restored (defined either in stylesheets or by
 * the browser's default style rules.)
 *
 * Caveat 1: if the inherited display property for the element is set to "none"
 * by the stylesheets, that is the property that will be restored by a call to
 * showElement(), effectively toggling the display between "none" and "none".
 *
 * Caveat 2: if the element display style is set inline (by setting either
 * element.style.display or a style attribute in the HTML), a call to
 * showElement will clear that setting and defer to the inherited style in the
 * stylesheet.
 * @param {Element} el Element to show or hide.
 * @param {*} display True to render the element in its default style,
 * false to disable rendering the element.
 */
var showElement = function(el, display) {
  el.style.display = display ? '' : 'none';
};

var myElement = document.getElementById('someID');
showElement(myElement, false);// it should now be hidden.

关于javascript - Div 样式未定义(Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14335071/

相关文章:

javascript循环没有给出预期的结果

流体网格内的 CSS Force 图像使用 IceCream 调整到父级高度

php - 获取选择框选项值不起作用

python - 将行为添加到外部模块返回的对象的 pythonic 方法是什么?

javascript - 如何使终端可滚动?

javascript - 网站 javascript 中的完整背景

javascript - 无法在主干 View 中定义两个事件

html - Div 为父级的 100%

css 继承上面的样式

类层次结构中的 Java 可选接口(interface)