繁体   English   中英

如何扩展此JavaScript以使其适用于多个项目?

[英]How can I extend this JavaScript to work for more than one item?

我找到了一个解决方案,该解决方案允许我单击某个区域以使用JavaScript显示工具提示,但仅适用于第一项。 这是解决方案。

这是代码:

 <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 = event.clientY + 15 + 'px'; tip.style.left = event.clientX + 10 + '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; position: absolute; } </style> <map> <area class="quick-tip" shape="poly" data-tip="THIS IS THE TIP! change elements 'data-tip' to change." data-tip-on="false"/> <area class="quick-tip" shape="poly" data-tip="THIS IS THE TIP! change elements 'data-tip' to change." data-tip-on="false"/> </map> <script> enableTips(); </script> 

只有最上面的一个起作用,最下面的什么都不起作用。 我需要的功能是两个按钮都可以在单击时显示工具提示。 我尝试将不同解决方案的其他部分拼接在一起都无济于事。 我也尝试过其他解决方案,但似乎没有任何解决方案。

我已经修改了原始解决方案,并使用了<area>因为将鼠标悬停在<area>上时,页面最初会弹出工具提示。 需要像解决方案中一样更改悬停功能以单击,但是第一个是唯一可用的功能。

你有错字

elems[0].addEventListener("click", doTip, false);

应该

elems[i].addEventListener("click", doTip, false);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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