Javascript工具提示不适用于chrome

时间:2011-11-08 15:27:00

标签: javascript html css

基于下拉列表的工具提示,适用于除Chrome以外的所有浏览器

function showTip(oSel) {
  var theTip = document.getElementById("spnTip");
  theTip.style.top = window.event.clientY + 20;
  theTip.style.left = window.event.clientX;
  theTip.innerText = oSel.options[oSel.selectedIndex].text;
  theTip.style.visibility = "visible";
}

function hideTip() {
  document.getElementById("spnTip").style.visibility = "hidden";
}
<select onmouseout="hideTip()" onmouseover="showTip(this)" style="width:100px;">
  <option>Have you seen the latest M. Night Shyamalan film?</option>
  <option>It's called The Village.</option>
  <option>Although the critics didn't like it, I think it was extremely well done.</option>
  <option>You will be kept in suspense even if you think you have figured out the ending.</option>
</select>
<span onmouseout="hideTip()" style="position:absolute; top:-35px visibility:hidden; background:#fefed5;
 border:1px solid #666666; padding:2px; font-size:12pt; font-family:Tahoma;" id="spnTip"></span>

1 个答案:

答案 0 :(得分:0)

您的代码中存在许多错误。我将解决一些问题。

innerText在Firefox中不起作用。你需要使用textContent。 另外,window.event不会在firefox中返回任何内容。您需要附加到函数调用返回的事件对象。 (我做对了吗?)

以下是将事件绑定到函数,并使用事件对象和 this 的示例。 因为我们将函数附加到select元素上调用的事件, this 将指向该元素。因此,我们不需要将它传递给函数。

var showTip = function(event) {
    var theTip = document.getElementById("spnTip");
    theTip.style.top = event.clientY + 20 + "px";
    theTip.style.left = event.clientX + "px";
    theTip.innerText = theTip.textContent = this.options[this.selectedIndex].innerText || this.options[this.selectedIndex].textContent;
    theTip.style.display = "block";
    theTip.addEventListener("mouseout", hideTip, false);
};
var hideTip = function() {
    this.style.display = "none";
};


var sel = document.getElementById("selectId");
sel.addEventListener("mouseover", showTip, false);

您还需要为IE添加投诉代码。

<select id="selectId" style="width:100px;">
<option>Have you seen the latest M. Night Shyamalan film?</option>
<option>It's called The Village.</option>
<option>Although the critics didn't like it, I think it was extremely well done.</option>
<option>You will be kept in suspense even if you think you have figured out the ending.</option>
</select>
<span style="position:absolute; top:-35px; display: none; background:#fefed5;
 border:1px solid #666666; padding:2px; font-size:12pt; font-family:Tahoma;" id="spnTip"></span>

demo here