开发者

jquery optimising hover event with div and an image

开发者 https://www.devze.com 2023-01-17 03:12 出处:网络
code: $(\'.featured\').hover( function() { $(this).addClass(\'active\'); $(\'img\',this).fadeTo(\'slow\', 0.5, function() {})

code:

    $('.featured').hover(
    function() {
        $(this).addClass('active');
        $('img',this).fadeTo('slow', 0.5, function() {})
    },
    function() {
        $(this).remove开发者_如何转开发Class('active');
        $('img',this).fadeTo('slow', 1, function() {})
    });

how can I improve this?

I recall someone telling me once not to use

$('img', this) ..

but I can't figure out how to access an image within the DIV being hovered over any other way.

thanks !


You can use .find(), like this:

$('.featured').hover(function(event) {
    $(this).addClass('active').find('img').fadeTo('slow', 0.5);
}, function() {
    $(this).removeClass('active').find('img').fadeTo('slow', 1);
});

This finds any <img> elements within the element you're hovering...skipping several steps $(selector, context) has to take to figure out it's really a $(context).find(selector) call. Also there's no need for the animation callbacks...they're optional so just leave them off if you're doing anything in them.

0

精彩评论

暂无评论...
验证码 换一张
取 消