gpt4 book ai didi

javascript - jQuery 对图像的悬停效果

转载 作者:行者123 更新时间:2023-11-30 16:24:10 27 4
gpt4 key购买 nike

我正在尝试使用 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事件就是不起作用。我不知道该怎么办。

如有任何帮助,我们将不胜感激!

编辑:哦,这里是 the JSFiddle , 以防万一

最佳答案

先说个小题外话……
你想做的事情可以仅使用 CSS:hover pseudo

轻松完成

.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>


回答你的 jQuery 问题

$("#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"
}
});

});

关于javascript - jQuery 对图像的悬停效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34346660/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com