سؤال

I am trying to add a 'read more' text when someone mouseovers my blog post's title. I tried using $(".blogpost").mouseover(function(){ $(this).append(" - read more..."); }); But i don't know how to remove the read more... when onmouseout.

هل كانت مفيدة؟

المحلول

Add read more in span and remove that span on mouse out

Add read more wrapped in span.

$(".blogpost").mouseover(function(){ $(this).append("<span id="read" - read more..."></span>); });

Remove added span with its id which is read in this case.

$(".blogpost").mouseout(function(){ $('#read').remove(); });

نصائح أخرى

The proper way to do this is just have the extra text in the HTML already and use a CSS :hover property to hide and show the text. Using javascript for this adds an unnecessary level of complexity and brittleness.

You can try this too:

$(".blogpost").mouseout(function(){ 
    $(this).html("");
});

Assuming you have no child elements.

If you want to do this in javascript, You can do something like this :

Demo : http://jsfiddle.net/a3jzF/

$(".blogpost").mouseover(function() { 
    $(this).append("<div class='readmore'> - read more...</div>"); 
}).mouseout(function(){
    $('.readmore').remove();        
});​

I would only show and hide it once it's created. .hover() takes two functions.

$(".blogpost").hover(function(){
  var $span = $(this).find('.more');

  if ( $span.length ) {
     $span.show();
  } else {
    $(this).append('<span class="more"> - read more...</span>');
  }

}, function(){
  var $span = $(this).find('.more');
  $span.hide();
});

Or use css only (this is better):

<div class="blostpost">
 ...
 <span class="more">read more</span>
</div>

.blogpost .more { display: none; }
.blogpost:hover .more { display: block; }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top