Plain JavaScript tooltip

前端 未结 5 2020
渐次进展
渐次进展 2020-12-08 01:16

I am trying to make a tooltip in plain JavaScript which is shown on hover. Like the one in Stack Overflow on hover over the profile name a div is s

5条回答
  •  臣服心动
    2020-12-08 01:30

    Solution with no JavaScript

    This uses CSS pseudo hover to set the display of the hidden element. The display none needs to be in the style and not on the element so it can be overwritten in the hover.

    HTML:

    First Link Content 1
    Second Link Content 2

    CSS:

    .couponcode:hover .coupontooltip { /* NEW */
        display: block;
    }
    
    
    .coupontooltip {
        display: none;  /* NEW */
        background: #C8C8C8;
        margin-left: 28px;
        padding: 10px;
        position: absolute;
        z-index: 1000;
        width:200px;
        height:100px;
    }
    
    .couponcode {
        margin:100px;
    }
    

    Example:

    jsFiddle

    Follow-Up:

    If you need to support really old browsers, you would need to add a class to the outside element when the mouse enters the div. And remove that class when mouse leaves.


    EDIT

    Your code did not work because what is tp? Is a collection of elements and you are treating it as one. What you would need to do is pass in the reference to the element

    HTML:

    **JavaScript:

    //var name = document.getElementsByclassName("name");  /* not needed */
    //    var tp = document.getElementsByclassName("tooltip"); /* not needed */
    
    
    function show (elem) {  /* added argument */
        elem.style.display="block"; /* changed variable to argument */
    }
    function hide (elem) { /* added argument */
        elem.style.display="";  /* changed variable to argument */
    }
    

提交回复
热议问题