简体   繁体   中英

How to show/hide a span using javascript

Can someone show a way to show/hide a span using javascript

 document.getElementById("test").style.display= 'visible';
 document.getElementById("test").style.display= 'block';

In the HTML Code

<span id='test' ..

How can I overcome this problem. Is there any thing that I should think about?

UPDATE I have a class like this one, I want to force mouse hovering on it.

<div id="test" class="tooltip effect">
        <div id="second" href="#"> .. </div>

On css:

tooltip{..}
effect{..}
effect:hover{..}

Another option I tried besides your code is

document.getElementById("test").onmouseover = test.hover;
  • Should I re-write the hover class to another name-class, or should I tweak your code?

Use display none/default:

document.getElementById("test").style.display= 'none';
document.getElementById("test").style.display= '';

Below are some types and some easy to remember rules about them:

Default: the elements default property (generally block or inline)

Block: Generally on a line by itself. Has the width and height attributes (among other size/positioning attributes)

inline: on the same line as other elements/text. Does not have height/width attributes

Inherit: Inherits the parent element's display type

visible不是显示一个值,你想none

I would do something like this to handle it:

function HideAndSeek(selector) {

    var elements = undefined;
    var displays = [];

    if (!!selector.id) {
        elements = [document.getElementById(selector.id)];
    } else if (!!selector.class) {
        elements = document.getElementsByClass(selector.class);
    }

    for (var elementIndex = 0; elementIndex < elements.length; elementIndex++) {
        displays[elementIndex] = elements[elementIndex].style.display;
    }

    this.hide = function() {
        for (var elementIndex = 0; elementIndex < elements.length; elementIndex++) {
            elements[elementIndex].style.display = "none";
        }
    };

    this.show = function() {
        for (var elementIndex = 0; elementIndex < elements.length; elementIndex++) {
            elements[elementIndex].style.display = displays[elementIndex];
        }
    };
}

This function can be used this way:

var hideAndSeek = new HideAndSeek({id: "test"});

and you can hide the element(s) by:

hideAndSeek.hide();

you can show them by:

hideAndSeek.show();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM