开发者

Hover over any paragraph, append div with little message, hover off, it fades out, is this right?

开发者 https://www.devze.com 2023-02-11 15:52 出处:网络
http://jsfiddle.net/nicktheandroid/3AraQ/ When a P is hovered over, #both is appended to that paragraph and centered. When i hover off and then onto a new paragraph, it fades out on the first P and f

http://jsfiddle.net/nicktheandroid/3AraQ/

When a P is hovered over, #both is appended to that paragraph and centered. When i hover off and then onto a new paragraph, it fades out on the first P and fades in on the now hovered P. is this the best way to do it? Later on i'll use this to allow people t开发者_StackOverflow社区o click a bookmark image, then when they hover a P it will do what my code below does, then when they click on that P it will create a bookmark to that paragraph, but I really just need help with the code below. THANKS!

$('p').hover(function() {

    $(this).append('<span id="both">BOOKMARK THIS</span>')
        $('#both').animate({opacity: 1.0}) 

}, function(){
        $('#both').fadeOut(600, function(){
            $(this).remove()
        })
});

it's not working smoothly, it's just not right....


Just use class instead of id:

$('p').hover(function() {

    $(this).append('<span class="both">BOOKMARK THIS</span>')
        $('.both').animate({opacity: 1.0}) 

}, function(){
        $('.both').fadeOut(600, function(){
            $(this).remove()
        })
});

http://jsfiddle.net/yzXxH/


I'd probably change it a little:

$('p').hover(function() {

    $('<span class="both">BOOKMARK THIS</span>')
        .appendTo(this)
        .animate({opacity: 1.0}) 

}, function(){

    var both = $(this).find('span.both');
    both.fadeOut(600, function(){
        both.remove()
    });

});

The reason I used a class instead of an id is that when you leave one paragraph and enter the next, you're going to temporarily have two of these spans — the one that's fading out on the old paragraph and the one added to the new one. Having two elements with the same id is invalid and fraught with peril.

I'd probably also cancel the animation early if I come back to the same paragraph:

$('p').hover(function() {

    $(this).find('span.both').stop().remove(); // Stop and remove it if it's there
    $('<span class="both">BOOKMARK THIS</span>')
        .appendTo(this)
        .animate({opacity: 1.0}) 

}, function(){

    var both = $(this).find('span.both');
    both.fadeOut(600, function(){
        both.remove()
    });

});


It doesn't look to me like you have a need to keep adidng and removing to the dom. Just put the span in by default with style="display:none;", then

$('p').hover(function() {
        $(this).find('#both').animate({opacity: 1.0}) 

}, function(){
        $(this).find('#both').fadeOut(600)
});

That won't work exactly, you may have to mess with opacity in the default style to get what you want. Still, no need to manipulate the dom.

0

精彩评论

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

关注公众号