2012-12-12 38 views
0

我剛寫了一個非常簡單的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:

http://jsfiddle.net/aVCtA/11/

,你看我的文字移動時的最後.highlight跨度消失。爲什麼?思想相對和Z指數:-1會解決這個問題嗎?

我應該改用位置絕對值並計算位置嗎?

回答

1

做了一些修改代碼,檢查test on jsfiddle

更新日誌:

jQuery的

刪除從以下行.css()

$this.width(newWidth + 2); 

CSS

改變造型來,

.highlight{ 
    background: #FBB829; 
    display: inline-block; 
    position: absolute; 
    z-index: -1; 
    top: 0px; 
    margin-left: -2px; 
    -moz-border-radius: 4px; 
    border-radius: 4px; 
} 
+0

非常感謝: – Muqito

+0

不客氣:) –

1

最簡單的解決方案是在淡出後不刪除高光元素。你可以通過改變你的淡出爲動畫不透明實現這一點:

$this.delay(Math.ceil(Math.random()*30)*200+2000).animate({opacity: 0},4000); 

這不是最漂亮的解決方案,但你的目的,我認爲這是確定。

+0

謝謝,欣賞它:)但是我確實想在之後刪除它。 – Muqito

0

這裏是另一種解決方案:

http://jsfiddle.net/aVCtA/20/

刪除CSS:

top:5px 

JS變化:

刪除了高度設置的線 添加了一個空白區域來設置其他字符的高度。 刪除額外的寬度,所以它不會在隱藏時移動。