頁面結構是 div → table → tr → td,需求是滑鼠移入 td 中的縮圖時顯示大圖,移出即消失。以下拆解實作步驟。
語法是 $(html標籤),例如這裡建立一個 img 節點:
var img = $("<img class='changePhoto'></img>");
hover 的語法為 $(selector).hover(inFunction, outFunction),分別對應 mouseenter 與 mouseleave。inFunction 是必填,outFunction 可選;若只傳一個函式,它會同時綁定到兩個事件上。
這裡 inFunction 負責決定大圖位置並插入節點,outFunction 則移除該節點。
只建立物件還不夠,必須掛到文件上才會顯示。jQuery 提供四個插入方法:
img.attr("src", $element.find(".prePhoto").attr("src"));
$element.append(img);
定位需要三個資訊:參照元素(這裡取 td 的父層 tr)、目標元素(img)、以及可出現的區域元素(table 的父層 div)。
var $element = $(this).parents("tr");
function getPosition($element, img, $container){
// top = 參照元素的 top + 參照元素自身高度
var top = $element.position().top + $element.height();
var maxBottom = $container.height(); // 區域元素高度
var minTop = 40;
// 若超出底部,改顯示在參照元素上方
if (top + img.height() > maxBottom) {
top = $element.position().top - img.height();
}
// 兩個判斷確保無論滾動條如何捲動,大圖都留在視線內
if (top < minTop) {
top = minTop;
}
var $firstElement = $($container.find("tbody tr")[0]);
img.css('top', top - $firstElement.position().top + 40);
}
$element.remove();
因為要依 JS 計算的位置顯示,必須絕對定位,並用 z-index 壓在表格之上。
.changePhoto {
position: absolute;
width: 120px;
height: 160px;
left: 300px;
right: 10px;
float: right;
z-index: 9;
}
整體流程串起來就是:hover 進入時建立 img、設定 src、計算座標後 append 進去;hover 離開時把節點移除。由於每次進入都重新建立節點,不必擔心狀態殘留,也不必處理同一時間出現多张大圖的問題。