DIV CSS 佈局教程網

滑鼠移入縮圖顯示大圖:jQuery hover 與定位實作
編輯:關於JavaScript     

頁面結構是 div → table → tr → td,需求是滑鼠移入 td 中的縮圖時顯示大圖,移出即消失。以下拆解實作步驟。

一、用 jQuery 建立元素

語法是 $(html標籤),例如這裡建立一個 img 節點:

var img = $("<img class='changePhoto'></img>");

二、hover 控制顯示與隱藏

hover 的語法為 $(selector).hover(inFunction, outFunction),分別對應 mouseenter 與 mouseleave。inFunction 是必填,outFunction 可選;若只傳一個函式,它會同時綁定到兩個事件上。

這裡 inFunction 負責決定大圖位置並插入節點,outFunction 則移除該節點。

三、把元素放進文件

只建立物件還不夠,必須掛到文件上才會顯示。jQuery 提供四個插入方法:

  • append():插入到被選元素結尾
  • prepend():插入到被選元素開頭
  • after():插入到被選元素之後
  • before():插入到被選元素之前
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 離開時把節點移除。由於每次進入都重新建立節點,不必擔心狀態殘留,也不必處理同一時間出現多张大圖的問題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved