[英]jQuery hover effect on image
我試圖在圖像上使用jQuery獲得簡單的懸停效果。 我最終想要得到的是綠色的懸停效果,文字和顏色一起出現。 我不知道我是否很清楚。
現在,我只希望簡單的顏色懸停效果起作用。
這是我首先要做的:
$("img").hover(
function() {
wid = $(this).width();
hei = $(this).height();
$("<div id='hover'></div>").insertBefore(this);
$("#hover").css({
"background-color": "rgba(60,147,138,0.2)",
"width": wid,
"height": hei,
"z-index": "3",
"position": "absolute"
});
},
function() {
$("#hover").remove();
}
);
那里的代碼在具有透明綠色背景的圖像上方生成了一個空的div,以獲得綠色懸浮效果。 但這並不能很好地工作,我的猜測是鼠標不再位於圖像上,而是位於它上方的那個div上。
所以我嘗試了這個:
$("img").mouseenter(
function() {
wid = $(this).width();
hei = $(this).height();
$("<div id='hover'></div>").insertBefore(this);
$("#hover").css({
"background-color": "rgba(60,147,138,0.2)",
"width": wid,
"height": hei,
"z-index": "3",
"position": "absolute"
});
}
);
$("#hover").mouseleave(
function() {
$(this).remove();
}
);
懸停效果如我預期的那樣穩定,但是mouseleave事件只是不起作用。 我不知道該怎么辦。
任何幫助,將不勝感激!
編輯:哦,這是JSFiddle ,以防萬一
首先是一個小題外話...
僅使用CSS和:hover
偽函數即可輕松完成您要嘗試執行的操作
.imgWrapper, .imgWrapper img{ position:relative; display:inline-block; vertical-align:top; } .imgWrapper span{ position:absolute; z-index:1; top:0; bottom:0; left:0; right:0; background:rgba(60,147,138,0.2); padding:24px; text-align:center; color:#fff; opacity:0; transition: 0.3s; font-size:2em; } .imgWrapper:hover span{ opacity:1; }
<span class="imgWrapper"> <img src="http://lemagcinema.fr/wp/wp-content/uploads/2014/11/alain_delon_59055-1024x768-500x372.jpg" width="300"> <span>This is an<br>image caption!</span> </span>
$("#hover").mouseleave(
在您分配該功能時,頁面上沒有#hover
元素。
這樣做:
$("img").mouseenter(function() {
var wid = $(this).width();
var hei = $(this).height();
$("<div id='hover' />").insertBefore(this);
$("#hover").css({
"background-color": "rgba(60,147,138,0.2)",
"width": wid,
"height": hei,
"z-index": "3",
"position": "absolute"
}).mouseleave(function() {
$(this).remove();
});
});
甚至更好的是,您根本不需要#ID: https : //jsfiddle.net/q5r3a00x/5/
$("img").mouseenter(function() {
var wid = $(this).width();
var hei = $(this).height();
$("<div />", {
insertBefore : this,
mouseout : function(){
$(this).remove();
},
css : {
backgroundColor: "rgba(60,147,138,0.2)",
width: wid,
height: hei,
position: "absolute"
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.