我有圖像作爲我的網站菜單按鈕,並且我想在用戶將其懸停或打開頁面時將圖像更改爲另一圖像。jquery懸停更改圖像src顯示空圖像
所以,我設置我的_Layout.cshtml懸停功能:
<div id="menubutton">
<a href="@Url.Action("Index", "Home")" id="bg1">
<img src="@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString() + "/Content/New_Layout/homebutton.png")" alt="home" id="homebutton" />
</a><a href="@Url.Action("Index", "Kitchen")" id="bg2">
<img src="@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString() + "/Content/New_Layout/kitchenbutton.png")" alt="kitchen" id="kitchenbutton" />
</a><a href="@Url.Action("Index", "Stock")" id="bg3" >
<img src="@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString() + "/Content/New_Layout/stockbutton.png")" alt="stock" id="stockbutton" /></a>
<a href="@Url.Action("Index", "Shop")" id="bg4" >
<img src="@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString() + "/Content/New_Layout/shopbutton.png")" alt="shoppinglist" id="shopbutton" /></a>
<a href="@Url.Action("Index", "Recipe", new { id = 0 })" id="bg5" >
<img src="@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString() + "/Content/New_Layout/recipebutton.png")" alt="recipe" id="recipebutton" /></a>
<a href="@Url.Action("Index", "Report")" id="bg6" >
<img src="@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString() + "/Content/New_Layout/reportbutton.png")" alt="report" id="reportbutton" /></a>
<a href="@Url.Action("Index", "Notification")" id="bg7" >
<img src="@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString() + "/Content/New_Layout/notificationbutton.png")" alt="notification" id="notificationbutton" /></a>
<a href="@Url.Action("Index", "Information", new { id = 0})" id="bg8" >
<img src="@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString() + "/Content/New_Layout/infobutton.png")" alt="info" id="infobutton" /></a>
</div>
// Store the old src of the image before hover to reapply after hover
var oldsrc = "";
$('#menubutton img').hover(
function() {
var name = $(this).attr('id') + '_o';
oldsrc = $(this).attr('src');
var newsrc = '@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString())' + '/Content/New_Layout/' + name + '.png';
$(this).attr('src', newsrc);
},
function() {
var name = $(this).attr('id');
//var newsrc = '@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString())' + '/Content/New_Layout/' + name + '.png';
$(this).attr('src', oldsrc);
}
);
(注:我使用AppSettings得到部署後正確的圖像路徑)
而且在每一個頁面,我想設置圖像,以突出顯示當前頁面用戶:
$('#bg4 img').attr('src', '@(System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString() + "/Content/New_Layout/shopbutton_o.png")');
目前,它似乎工作正常。但是,如果圖像懸停多次觸發,則圖像src將變爲「」,因此圖像消失。
我找不到原因,所以希望可以在這裏一些幫助......
非常感謝您
謝謝!到目前爲止這麼好,你只是介紹一種我從未注意過的新jQuery方法!謝謝:) – shennyL 2011-12-16 06:11:02