【问题标题】:How to make this tooltip like this with pure javascript如何使用纯 JavaScript 制作这样的工具提示
【发布时间】:2013-11-22 21:12:23
【问题描述】:

我需要使用 JS 没有 JQuery 插件来制作一个简单的工具提示,如下图所示。

单击 ? 图像应打开此工具提示,然后再次单击同一图像将其关闭。 我认为对于具有良好 JS 知识的人来说这很简单,但无论如何我都做不到:(

这是我尝试过的东西,我知道这并不过分,但我只是卡住了。
如何在图片上显示它,打开时如何隐藏它,以及如何在角落添加那个小三角形?

myfiddle

<img id="info" src="http://www.craiglotter.co.za/wp-content/uploads/2009/12/craig_question_mark_icon1.png"/>
<div id="ttip">bla bla</div>

document.getElementById('info').addEventListener('click', function(){
    // how to check if it's visible so I can close tooltip
    document.getElementById('ttip').style.display="block";    
});

#info{margin-left:100px;margin-top:50px;}
#ttip
{
    width: 280px;
z-index: 15001;
top: 0px;
left: 0px;
display: none;
    border-color: #666;
background-color: #fff;
color: #666;
    position: relative;
border: 1px solid #666;
padding: 15px 9px 5px 9px;
text-align: left;
word-wrap: break-word;
overflow: hidden;
}

【问题讨论】:

  • 你需要解释你的知识基础,你知道如何做这部分,当你搜索时你发现了什么,以及这个问题的哪一部分你特别需要帮助。换句话说,您需要证明您至少已经为开始这里付出了一些基本的努力,然后向我们展示您遇到的问题。
  • 我尝试过使用 JQuery 插件,但效果不佳,因为我需要纯 JavaScript。我尝试了一些东西,但没有真正得到任何东西。我知道只是在点击时显示 div 而不是像这样用箭头指向被点击的图像来显示它。所以我没有类似的东西:(
  • 我很惭愧。我更新了我知道的问题;不是太多,但不能做出我想要的。我很少使用 js。
  • @1110 现在应该可以解决问题了:jsfiddle.net/u93a3/1

标签: javascript html css dom-events tooltip


【解决方案1】:

清理css,基本上就可以了:

<script>
    function doTip(e){
          var elem = e.toElement;
          if(elem.getAttribute('data-tip-on')  === 'false') {

            elem.setAttribute('data-tip-on', 'true');
            var rect = elem.getBoundingClientRect();          
            var tipId = Math.random().toString(36).substring(7);
            elem.setAttribute('data-tip-id', tipId);
            var tip = document.createElement("div");
            tip.setAttribute('id', tipId);
            tip.innerHTML = elem.getAttribute('data-tip');
            tip.style.top = rect.bottom+ 10 + 'px';
            tip.style.left = (rect.left-200) + 'px';
            tip.setAttribute('class','tip-box');
            document.body.appendChild(tip);

          } else {

            elem.setAttribute('data-tip-on', 'false');
            var tip = document.getElementById(elem.getAttribute('data-tip-id'));
            tip.parentNode.removeChild(tip);


          }
    }
    function enableTips(){
        var elems = document.getElementsByClassName('quick-tip');
        for(var i = 0; i < elems.length; i++) { 
            elems[0].addEventListener("click", doTip, false);

        }
    }
    window.onload = function(){
        enableTips();
    }
</script>
<style>
    .quick-tip {
        background: black;
        color: #fff;
        padding: 5px;
        cursor: pointer;
        height: 15px;
        width: 15px;
        text-align: center;
        font-weight: 900;
        margin-left: 350px;

    }
    .tip-box {
    /* change dimensions to be whatever the background image is */
        height: 50px;
        width: 200px;
        background: grey;
        border: 1px solid black; 
        position: absolute;
    }
</style>


<div class="quick-tip" data-tip="THIS IS THE TIP! change elements 'data-tip' to change." data-tip-on="false">?</div>

<script>enableTips(); //might be required for jsfiddle, especially with reloads.</script>

编辑:固定格式和错误。 jsfiddle:http://jsfiddle.net/u93a3/

【讨论】:

  • window.onload 在 jsfiddle 中不会一直触发。将此添加到 html 的底部以确保它将:&lt;script&gt;enableTips();&lt;/script&gt;
  • 这是提示正确背景的小提琴:jsfiddle.net/u93a3/1
  • 啊谢谢我只是想改变你的代码来添加那个三角形。谢谢。我将从这段代码中学到很多东西。再次感谢。
  • 我将尝试扩展它以不使用图像作为背景,而是以某种方式添加带有 css 的右角三角形。
  • 唯一的问题是,这在 IE 中也不起作用,它表明 IE 无法识别 addEventListener...
【解决方案2】:

概念证明:

HTML 中的以下标记:创建一个类为 tooltip 的 div,添加图片和一个类为 info 的 div,其中包含所有文本(如果需要,可以是多个段落,如果需要,会显示 scollbars):

<div class='tooltip'>
  <img src='craig_question_mark_icon1.png' alt='Help'/>
  <div class='info'>
    Some text to fill the box with.
  </div>
</div>

div.info 在 CSS 中设置为 display:none

当页面被加载时,一个纯 javascript 正在运行,它在画布元素上绘制一个三角形的图像,然后创建一个 div 元素,其中三角形设置为背景。然后,对于每个div.tooltip

  1. 向图像添加点击事件处理程序
  2. div.info 替换为div.info_container
  3. 将三角形div的克隆添加到div.info_container
  4. 将原来的div.info添加到div.info_container

您可以使用此fiddle 对其进行测试。在FF25、Chrome31、IE10、Opera 12&18上测试成功。

<!doctype html>
<html>
  <head>
    <script>
      "use strict";
      function click(event) {
        var elem = this.parentNode.querySelector('div.info_container');
        if (elem) elem.style.display = elem.style.display === 'block' ? 'none' : 'block';
      }
      function toolify() {
        var idx,
            len,
            elem,
            info,
            text,
            elements = document.querySelectorAll('div.tooltip'),
            canvas,
            imgurl,
            pointer,
            tipHeight = 20,
            tipWidth = 20,
            width = 200,
            height = 100,
            ctx;

        // Create a canvas element where the triangle will be drawn
        canvas = document.createElement('canvas');
        canvas.width = tipHeight;
        canvas.height = tipWidth;
        ctx = canvas.getContext('2d');

        ctx.strokeStyle = '#000';   // Border color
        ctx.fillStyle = '#fff';     // background color
        ctx.lineWidth = 1;

        ctx.translate(-0.5,-0.5);   // Move half pixel to make sharp lines
        ctx.beginPath();
        ctx.moveTo(1,canvas.height);              // lower left corner
        ctx.lineTo(canvas.width, 1);              // upper right corner
        ctx.lineTo(canvas.width,canvas.height);   // lower right corner
        ctx.fill();                               // fill the background
        ctx.stroke();                             // stroke it with border
        //fix bottom row
        ctx.fillRect(0,canvas.height-0.5,canvas.width-1,canvas.height+2);

        // Create a div element where the triangel will be set as background
        pointer = document.createElement('div');
        pointer.style.width = canvas.width + 'px';
        pointer.style.height = canvas.height + 'px';
        pointer.innerHTML = '&nbsp;' // non breaking space
        pointer.style.backgroundImage = 'url(' + canvas.toDataURL() + ')';
        pointer.style.position = 'absolute';
        pointer.style.top = '2px';
        pointer.style.right = '1px';
        pointer.style.zIndex = '1'; // place it over the other elements

        for (idx=0, len=elements.length; idx < len; ++idx) {
          elem = elements[idx];
          elem.querySelector('img').addEventListener('click',click);
          text = elem.querySelector('div.info');
          // Create a new div element, and place the text and pointer in it
          info = document.createElement('div');
          text.parentNode.replaceChild(info,text);
          info.className = 'info_container';
          info.appendChild(pointer.cloneNode());
          info.appendChild(text);
          //info.addEventListener('click',click);
        }
      }
      window.addEventListener('load',toolify);
    </script>
    <style>
      div.tooltip
      {
        position:relative;
        display:inline-block;
        width:300px;
        text-align:right;
      }
      div.tooltip > div.info
      {
        display:none;
      }
      div.tooltip div.info_container
      {
        position:absolute;
        right:20px;
        width:200px;
        height:100px;
        display:none;
      }
      div.tooltip div.info
      {
        text-align:left;
        position:absolute;
        left:1px;
        right:1px;
        top:20px;
        bottom:1px;
        color:#000;
        padding:5px;
        overflow:auto;
        border:1px solid #000;
      }
    </style>
  </head>
  <body>
    <div class='tooltip'>
      <img src='craig_question_mark_icon1.png' alt='Help'/>
      <div class='info'>
        Some text to fill the box with.
      </div>
    </div>
    <div class='tooltip'>
      <img src='craig_question_mark_icon1.png' alt='Help'/>
      <div class='info'>
        Some text to fill the box with.
        Some text to fill the box with.
        Some text to fill the box with.
        Some text to fill the box with.
      </div>
    </div>
  </body>
</html>

【讨论】:

  • 唯一的问题是这在 IE 中不起作用它接缝 IE 无法识别 addEventListener...
  • @1110 你运行的是什么版本?一直是supported since IE9。旧版本使用attachEvent(IE11 不支持attachEvent)
猜你喜欢
  • 1970-01-01
  • 2013-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 2018-06-25
  • 1970-01-01
相关资源
最近更新 更多