ryoakg
6/9/2016 - 11:18 AM

js-tooltip.html

<html>
  <head>
    <style>
     .tooltip-element{
       position:fixed;
       background:#fff;
       color:#000;
       border:1px solid #0080FF;
       padding:10px;
       margin:0px;
       text-align:left;
       line-height:1.2;
     }
    </style>
  </head>
  <body>
    <span tooltip-text="bar!">foo</span> hoo
    <ul>
      <li><span tooltip-text="red">赤</span></li>
      <li><span tooltip-text="blue">青</span></li>
      <li><span tooltip-text="green">緑</span></li>
    </ul>
    <script>
     var addEvent = document.addEventListener ?
                    function (node, type, listener){ node.addEventListener(type, listener, false); } :
                    function (node, type, listener){ node.attachEvent('on' + type, listener); };
     var TEXT = 'textContent' in document.documentElement ?
                'textContent' : 'innerText';

     var tooltipfy = (function(){
       var tooltip = document.createElement('div');
       tooltip.className = 'tooltip-element';
       tooltip.style.display = 'none';
       addEvent(window, 'load', function(){ document.body.appendChild(tooltip); });

       return function(element, text){
         addEvent(element, 'mouseover', function(ev){
           tooltip[TEXT] = text;
           tooltip.style.left = ev.clientX + 10 + 'px';
           tooltip.style.top  = ev.clientY + 10 + 'px';
           tooltip.style.display = 'block';
         });
         addEvent(element, 'mouseout', function(evt){
           tooltip.style.display = 'none';
         });
       };})();

     addEvent(window, 'load', function(){
       var xs = document.querySelectorAll('*[tooltip-text]');
       for (var i=0; i<xs.length; i++)
         tooltipfy(xs[i], xs[i].getAttribute('tooltip-text'));
     });
    </script>
  </body>
</html>