Jquery opacity change

2019-07-07 06:49发布

问题:

I have this code:

$('a[rel="imagesHandler"]').hover(
    function(){
        //ia latimea
        var liWidth = $(this).width();
        $(this).append('<div id="editBar"><a id="delPic" href="#"><img id ="piDe"src="./images/pic_del_icon.png" alt="" /></a></div>');

        $('div#editBar')
            .css({  'width':liWidth - 3,
                'height':'19px',
                'padding-left':'3px',
                'padding-top':'1px',
                'float':'left',
                'position':'relative',
                'top':'-22px',
                'z-index':200,
                'background-color':'black',
                'opacity':'0.5'
            })
            .hide()
            .fadeIn('slow');

        $('a#delPic').click(function(event){
            event.stopPropagation();
            alert('gigi');
            return false;
        });
    },
    function(){
        $('div#editBar').hide('slow');
        $('div#editBar').remove();
    }
);

So, i append that that pops on mouseover, inside this div is the a#delPic. I changed the opacity of div#editBar to 0.5 but it applies to a#delPic too. So, I want to change back the a#delPic opacity to 1. How can I do this? I tried some versions. That's why I ended up putting that id to the anchor (trying to directly select it), but still doesn't work.

回答1:

Opacity will be applied to all elements inside, you are not able to change this behaviour. But you can do a little trick:

$('a[rel="imagesHandler"]').hover(
function(){
    var liWidth = $(this).width();

    $(this).append('<div id="editBar"><div class="transparent"></div><a id="delPic" href="#"><img id ="piDe"src="./images/pic_del_icon.png" alt="" /></a></div>');

    $('div#editBar .transparent').css({
        'position': 'absolute',
        'left':'0',
        'right':'0',
        'top':'0',
        'bottom':'0',
        'background-color':'black',
        'opacity':'0.5'
    });

    $('div#editBar').css({'width':liWidth - 3,
        'height':'19px',
        'padding-left':'3px',
        'padding-top':'1px',
        'float':'left',
        'position':'relative',
        'top':'-22px',
        'z-index':200
    }).hide().fadeIn('slow');

    $('a#delPic').click(function(event){
    event.stopPropagation();
    alert('gigi');
    return false;
    });
},

function(){
    $('div#editBar').hide('slow');
    $('div#editBar').remove();
}

);



回答2:

You can't. Setting opacity on an element makes everything inside it follow that rule. One solution (not widely implemented yet) is to use rgba(r,g,b,o) which will set opacity for that one element alone.

Another solution is to create a black 1px png 8 (also supported in IE6) or gif that's 50% opaque. Set this as the background-image for the parent element, and you're good to go.



回答3:

Its because the a tag is within the div, when you apply an opacity change to an element it will affect all elements within it too.