[英]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.