0

Okay i am using the instagram's API to retrieve profile images and usernames. Moreover, i want the profile images to fade when the mouse hovers over it. However, that doesn't seem to work and I'm not sure if it's because the img is placed inside the script tag. I've been looking for hours for an answer but i couldn't find any. So i'd really appreciate it if someone helped me.

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

2 回答 2

3

您的图像是动态添加到 DOM 中的,因此您必须使用事件委托。但是,.hover它本身没有委托,因为它是mouseenterand的快捷方式mouseleave。使用这些事件进行委派:

$('#images').on({
    mouseenter : function(){
        $(this).fadeTo("fast",0.5);
    },
    mouseleave : function(){
        $(this).fadeTo("fast",1);
    }
}, '#img');

请注意,您正在附加多个具有相同 ID 的元素。ID 必须是唯一的,请改用类。

在此处阅读有关事件委托的信息。

于 2014-11-14T19:20:25.200 回答
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;
}
于 2014-11-14T19:27:07.960 回答