這篇不囉嗦,直接把關鍵步驟拆成四段說明,跟著做就能跑起來。
<script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src='js/jquery.thoughtBubble.js'></script>
氣泡會以某個元素為定位基準,所以要給它一個 id 方便稍後選取。
<div id='mainContainer' class='container'> <img src='ahout.JPG' id="thoughtBubble" alt='whats up?' /> </div>
<script type="text/javascript">
$(window).ready( function() {
$('#thoughtBubble').thoughtBubble({
text: 'baby,I love you',
font: 'avenir'
});
});
</script>
整個外掛的核心是動態組出氣泡的 DOM,再用 animate() 依序把大氣泡到小氣泡的透明度做遞進動畫,營造出泡泡由小到大飄出來的感覺;同時綁定 mouseenter 與 mouseout 控制顯示與隱藏,並在視窗 resize 時重新校正水平位置。
(function($) {
$.fn.thoughtBubble = function( defaults ) {
var settings = $.extend({
backgroundColor: 'white',
fontColor: 'black',
width: '330px',
height: '210px',
fontSize: '15px',
bubbleColor: 'white',
speed: 125
}, defaults ),
getBubbleDiv = function( container ) {
var offset = container.offset(),
modifiedHeight = offset.top - parseInt( settings.height ),
style = '"position: absolute; top:' + modifiedHeight + 'px; left:' + offset.left + 'px ; width:' + settings.width + '; height:' + settings.height + ';"',
bubbleContainer = "<div class='bubble-holder' style=" + style + ">" + getMainBubble() + getBubbles() + "</div>";
return bubbleContainer;
},
getMainBubble = function() {
return '<div class="main-bubble-holder"><div class="bubble main-bubble">' + getText() + '</div></div>';
},
getText = function() {
return '<span style="vertical-align: middle; color: ' + settings.fontColor + ';font-size: ' + settings.fontSize + '; font-family: ' + settings.font + '">' + settings.text + '</span>';
},
getBubbles = function() {
return '<div class="sm-bubble-holder"><div class="bubble bubbleLg"></div><div class="bubble bubbleMd"></div><div class="bubble bubbleSm"></div></div>';
},
animate = function(){
var bubbles = $(document).find('.bubble'),
reversed = bubbles.get().reverse(),
speed = settings.speed;
$(reversed[0]).stop().animate({ opacity: 1}, speed, function() {
$(reversed[1]).animate({ opacity: 1}, speed, function() {
$(reversed[2]).animate({ opacity: 1}, speed, function() {
$(reversed[3]).animate({ opacity: 1},speed);
});
});
});
},
unanimate = function() {
var bubbles = $(document).find('.bubble');
bubbles.stop().animate({opacity: 0});
},
shiftDiv = function( container ) {
var bubbleHolder = $(document).find('.bubble-holder'),
previousPosition = container.offset().left;
bubbleHolder.css('left', previousPosition);
};
return this.each( function() {
var $this = $(this),
container = getBubbleDiv( $this );
$this.on('mouseenter', animate );
$this.on('mouseout', unanimate );
$(window).on('resize', shiftDiv.bind(this, $this) );
return $this.parent().prepend(container);
});
};
})(jQuery);
以上就把 JS 氣泡效果的關鍵步驟分享完了,程式碼本身不長、也相當好懂,所以沒有再贅述太多文字。有疑問歡迎留言,我會盡快回覆,也感謝大家一路以來對網站的支持!