懸停時,以下代碼將獲取子菜單面板中最高的列,並將所有列設置爲相同的高度。它還獲取所有列的寬度之和設置列容器寬度的總和:獲取並設置懸停時元素的高度和寬度一次
$(function()
{
$("#menu> li").hover(function() {
var tallestColumnHeight = 0, submenuPanelTotalWidth = 0;
$("ul.sub-menu-1 > li", this).each(function() {
tallestColumnHeight = Math.max(tallestColumnHeight, $(this).height());
submenuPanelTotalWidth += parseInt($(this).outerWidth(), 10);
}).height(tallestColumnHeight);
$("ul.sub-menu-1 > li", this).parent().width(submenuPanelTotalWidth);
});
});
現在上面的代碼有很大的開銷,因爲它獲取和設置高度和寬度的兩倍每個徘徊。我想設置某種標誌,以便計算只運行一次。
任何想法?在這裏使用jQuery .data()來存儲初始值,然後檢查數據是否設置是否明智?
任何建議或幫助,這是非常感謝!
UPDATE
與的mouseenter()事件更換懸停()和使用一個()是最好的解決方案。
下面是更新後的代碼:
$(function()
{
$("#menu > li").one('mouseenter', function(e)
{
var tallestColumnHeight = 0,
submenuPanelTotalWidth = 0;
$("ul.sub-menu-1 > li", this).each(function()
{
tallestColumnHeight = Math.max(tallestColumnHeight, $(this).height());
submenuPanelTotalWidth += parseInt($(this).outerWidth(true), 10);
}).height(tallestColumnHeight);
$("ul.sub-menu-1 > li", this).parent().width(submenuPanelTotalWidth);
});
});
似乎已經在SO中討論過了。請參閱http://stackoverflow.com/questions/4638691/jquery-using-one-with -hover – Raghav
感謝Raghav,用mouseenter替換懸停並使用.one()是最好的方法。使用新代碼更新我的文章。 – IntricatePixels