简体   繁体   中英

centering variable width span on top fixed size image with jquery

Here is the jsfiddle

//Fade in and out animation on hove buttons - icon set, features.
$(window).load(function() {
    $("ul#features_icons li img").hover(function() {
        $(this).next("span").animate({ opacity: "show" }, "fast");
    }, function() {
        $(this).next("span").animate({opacity: "hide"}, "fast");
    });
});

I'm trying to accomplish a hover on effect, where contents of the span will be display:none, but as soon as you hover on it will become display:block. With css I managed to put it on the top of the image by using negative margin, but my problem is to center this span in relation to the image.

Any ideas?

with css it is not possible. So must be with jquery something?

Thanks!

demo jsFiddle

We have to calculate the center of the image (width/2) and the center of the span (width/2).
After we have this var s we can play with the span's marginLeft .

var spanW = 0;
var imgW = $('li img').width()/2;
$(window).load(function() {
    $("ul#features_icons li img").hover(function() {
        spanW = $(this).next("span").width()/2;
        $(this).next("span").css({marginLeft: -spanW-imgW }).stop().animate({ opacity: "show" }, "fast");
    }, function() {
        $(this).next("span").stop().animate({opacity: "hide"}, "fast");
    });
});

I even added the .stop() before your animations to prevent animation bubblings (fast mousemoves over your elements issue).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM