我剛寫了一個非常簡單的jQuery插件..有點,我想要一些幫助。修復我的jQuery高亮插件
(function($){
$.fn.highlight = function(words){
return this.each(function(){
//Get text from within
var text = $(this).html();
//Replace with new text
$(this).html(text.replace(words,"<i class='highlight'></i><span class='word'>"+"$1"+"</span>"));
//Get the all the highlight classes within this
var highlights = $(this).find(".highlight");
//Go through all
return highlights.each(function(){
var $this = $(this);
//Get to the next word
var wordDiv = $this.nextAll(".word").eq(0);
//Set highlight span same height as word
$this.height(wordDiv.height()+2);
//Set highlight span same width +4 then positioning
var newWidth = wordDiv.width()+4;
wordDiv.replaceWith(function(){
return $(this).contents();
});
$this.width(newWidth+2).css({
left:(newWidth)+"px",
marginLeft: "-"+(newWidth)+"px"
});
$this.delay(Math.ceil(Math.random()*30)*200+2000).fadeOut("4000",function(){
$this.remove();
});
});
});
}
})(jQuery);
$(document).ready(function(){
$("div").highlight(/(simple|wrote|knowledge)/g);
});
和CSS:
.highlight{
background: #FBB829;
display: inline-block;
position: relative;
z-index: -1;
top: 5px;
-moz-border-radius: 4px;
border-radius: 4px;
}
,並更好更好的做法是把那個CSS的jQuery插件? 這裏有一個的jsfiddle:
,你看我的文字移動時的最後.highlight跨度消失。爲什麼?思想相對和Z指數:-1會解決這個問題嗎?
我應該改用位置絕對值並計算位置嗎?
非常感謝: – Muqito
不客氣:) –