好的,我正在使用Instagram的API来检索个人资料图片和用户名。此外,我希望配置文件图像在鼠标悬停在其上时淡出。但是,这似乎不起作用,我不确定它是否是因为img被放置在脚本标记内。我一直在寻找答案的时间,但我找不到任何答案。如果有人帮助我,我真的很感激。
<script>
$(document).ready(function () {
$('#images').hover(function () {
$(".img").fadeTo("fast",0.5);
}, function () {
$(".img").fadeTo("fast",1);
});
$("input").keypress(function (event) {
if (event.which === 13) {
event.preventDefault();
$("#images").empty();
$.ajax({
type: 'GET',
url: 'get_info.php',
data: {keyword: $("input").val()},
dataType: 'JSON',
success:
function (jsonStr) {
$.each(jsonStr.data, function (index, element) {
$('#images').append("<div class='instaUser'><img class='img' src=" + element.profile_picture + " /><span class='username'>@" + element.username + "</span></div>");
});
}
});
}
});
});
</script>
答案 0 :(得分:3)
您的图像会动态添加到DOM中,因此您必须使用事件委派。但是,.hover
本身没有委派,因为它是mouseenter
和mouseleave
的快捷方式。使用这些事件进行委派:
$('#images').on({
mouseenter : function(){
$(this).fadeTo("fast",0.5);
},
mouseleave : function(){
$(this).fadeTo("fast",1);
}
}, '#img');
请注意,您要附加多个具有相同ID的元素。 ID必须是唯一的,而是使用类。
了解事件委托here.
答案 1 :(得分:1)
这里的其他答案都很好并且会解决你的问题,但是CSS转换会更好地处理这类事情。
首先,您要创建许多具有相同ID的元素,这是一个很大的禁忌,因为ID应该是页面唯一的。请改用类(我在以下代码段中更改的所有内容为id='img'
至class='img'
):
$('#images').append("<div id='instaUser'><img class='img' src=" + element.profile_picture + " /><span id='username'>@" + element.username + "</span></div>");
然后您可以使用CSS添加简单的不透明度转换:
.img {
// The normal, non-hovered opacity (100%)
opacity: 1.0;
// Cross-browser transition which animates the opacity of the image
// for 200 millisecons using an ease-in easing function.
-webkit-transition: opacity 200ms ease-in;
-moz-transition: opacity 200ms ease-in;
-ms-transition: opacity 200ms ease-in;
-o-transition: opacity 200ms ease-in;
transition: opacity 200ms ease-in;
}
.img:hover {
// The opacity you want to end at, so long as the mouse stays over the image (50%)
opacity: 0.5;
}