相当于.show() - 简单JavaScript中的jQuery

时间:2012-08-15 05:09:24

标签: javascript jquery css

任何人都知道javascript中jquery的等同于.show()吗?

我已经尝试过使用document.getElementById和添加/删除我命名为“show”//“hide”的类,但是效果不好我可能在这些类中有错误的属性我不确定..

节目类是:

.show{
    position:relative;
    display:block;
}

,隐藏类是:

.hide{
    position:absolute;
    top:0px;
    right:0px;
    display:none;
}

我很确定有更好的方法。

5 个答案:

答案 0 :(得分:13)

document.getElementById('myElement').style.display = 'block'; // show
document.getElementById('myElement').style.display = 'none'; // hide

答案 1 :(得分:4)

jQuery在隐藏之前考虑了display的价值。当您触发show()时,它会将其返回到该值。因此,不仅仅是将元素的display属性设置为blocknone

基本上是这样的:

function hide(){
    //get previous display value
    //store it in an internal cache. jQuery has an internal data storage
    //hide element
}

function show(){
    //get previous display value for that element
    //apply to element to show it
}

  

.show()

     

匹配的元素将立即显示,没有动画。这大致相当于调用.css('display', 'block'),除了显示属性恢复到最初的状态。如果某个元素的显示值为inline,则会隐藏并显示该元素,它将再次以内嵌方式显示。

答案 2 :(得分:0)

使用document.getElementById("MyId").className='show' document.getElementById("MyId").className='hide'

答案 3 :(得分:0)

尝试使用document.getElementsByClassName,因为您使用的是.show和.hide。这些是类,你试图通过Id来实现目标。免责声明:您可能需要仔细检查旧浏览器对此的支持。

答案 4 :(得分:0)

在jQuery之前,我使用以下方法来显示/隐藏元素:

HTMLElement.prototype.toggleDisplay = function(on_or_off, display_type) {
    if (typeof(tddisptype) == "undefined") tddisptype = "block";
    var new_display;
    if (typeof(on_or_off) != "boolean") {
        if (this.style.display == "none") new_display = display_type;
        else new_display = "none";
    } else {
        if (on_or_off) new_display = display_type;
        else new_display = "none";
    }
    this.style.display = new_display;
}​

这会为所有元素添加一个toggleDisplay()函数;例如,您可以通过document.getElementById()获得的。您可以将其作为参数传递truefalse来显示或隐藏元素,或者如果您不传递参数,它将尝试确定是否显示或隐藏元素。第二个参数指定与“on”状态关联的显示类型;上面,它默认为block