下面這個元件做出類似原生 title 的滑鼠移入提示效果,但內容可以是 HTML,還會自動判斷邊界避免溢出畫面。
function tips(obj, tag){
var tip = document.createElement('div'),
arg = arguments[2],
left, top;
var bodywid = document.documentElement.clientWidth; // 也可替換為容器寬度 $(id).outerWidth();
var abs = obj.getElementsByTagName(tag);
tip.className = "tip_bd";
obj.appendChild(tip);
for (var i = 0, len = abs.length; i < len; i++) {
hover(abs[i], function(){
var content = arg || this.getAttribute('tip'), text;
left = position(this).left;
top = position(this).top;
content ? tip.innerHTML = content : tip.innerHTML = "暫無內容!";
if (left + parseInt(getStyle(tip, 'width')) > bodywid) // 判斷是否超出最大寬度
text = 'right:' + (bodywid - left) + 'px;left:auto;';
else
text = 'left:' + (left + this.offsetWidth) + 'px;';
text += 'top:' + (top + this.offsetHeight) + 'px;';
tip.style.cssText = text;
text = '';
tip.style.display = 'block';
}, function(){
tip.style.display = 'none';
});
}
}
function hover(el, fnOver, fnOut){ // 滑鼠滑過
addEvent(el, 'mouseover', fnOver);
addEvent(el, 'mouseout', fnOut);
}
function addEvent(el, type, fn){ // 綁定事件
if (el.attachEvent) {
el['e' + type + fn] = fn; // IE 下拷貝元素參照,使 this 指向 el 而非 window
el[type + fn] = function(){ el['e' + type + fn](window.event); };
el.attachEvent('on' + type, el[type + fn]);
} else {
el.addEventListener(type, fn, false);
}
}
function position(el){ // 取得節點的絕對位置
if (el && el.nodeType == 1)
return {
'left': el.getBoundingClientRect().left + document.documentElement.scrollLeft,
'top': el.getBoundingClientRect().top + document.documentElement.scrollTop
};
}
function getStyle(obj, styleName){ // 取得目前樣式屬性
if (obj.currentStyle) // IE
return obj.currentStyle[styleName];
else { // 標準瀏覽器
var $arr = obj.ownerDocument.defaultView.getComputedStyle(obj, null);
return $arr[styleName];
}
}
tips(document.getElementById('tips'), 'a');
把上面另存為 tip.js,使用頁面如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>提示信息框</title>
<link rel="stylesheet" type="text/css" href="style/css/tip.css" />
<style>
#wrap { line-height:22px; padding:20px; }
#tips .tip_bd {
border: 1px solid green;
width: 100px;
position: absolute;
background: #fff;
z-index: 9999;
text-align: center;
display: none;
}
#tips { border: 1px solid #ccc; padding: 0 10px; }
</style>
</head>
<body>
<h1>提示信息框</h1>
<div id="tips">
閱讀了<a href="#" tip=""></a>今天發布的 IT 文章《30 個提高 Web 程式執行效率的好經驗》,這 30 條準則對我們 Web 開發非常有用,不然只是知其然而不知其<a href="#" tip="2"></a>所以然。下面是我對這些準則的理解和分析,有些關於 JS 性能的準則,我也測試了它們<a href="#"></a>的差異,大家可以下載 DEMO 頁面,如有理解不正確的地方,請大家指教。
</div>
</body>
<script type="text/javascript" src="tips.js"></script>
</html>
幾個實作細節值得說明:
el['e' + type + fn] 把 el 夾帶進來,才能在回呼中正確取到元素。tip 屬性。這讓同一份程式碼能同時處理「統一內容」與「各自內容」兩種需求。要注意的是,自訂的 tip 屬性並非標準 HTML,在今日應該改用 data-tip,並以 dataset.tip 讀取。另外把 content 直接塞進 innerHTML 有 XSS 風險——若內容可能來自使用者輸入,必須先轉義。最後,純滑鼠移入的提示對鍵盤使用者與行動裝置完全不可見,嚴肅的專案應該同時處理 focus/blur 事件,並給提示框適當的 role="tooltip"。