之前在寫一個界面,想要用到氣泡,然而一直找不到現成的有效地辦法,是在沒有辦法了我只好自己寫一個,於是就有了現在的CreateBubble.js。很簡單的一個函數,但是非常實用。
使用方法:
1.HTML代碼:
一個氣泡對話框就是一個div,div內嵌另一個div,很簡單的結構。
1 <div class="tag"> 2 css3氣泡框 3 <div class="tail"></div> 4 </div>
其中div的class或者id不限制,可以隨意給,也可以不定義。
函數源碼:
1 $.fn.createBubble = function(obj){ 2 $(this).each(function(k,v){ 3 var $tail = $(v).find('div'); 4 var doubleRadius = '-'+(parseInt((obj.radius).replace(/px/g,''))*2).toString()+'px'; 5 $(v).css({ 6 'width':obj.width, 7 'height':obj.height, 8 'background-color':obj.color, 9 'border-radius':obj.radius, 10 'position':'absolute', 11 'overflow':'visible' 12 }); 13 $tail.css({ 14 'position':'absolute', 15 'width':'0px', 16 'height':'0px', 17 'border':obj.tailSize + ' solid transparent' 18 }); 19 switch(obj.tailPosition){ 20 case 'top': $tail.css({'top':doubleRadius,'border-bottom-color':obj.color});break; 21 case 'right':$tail.css({'right':doubleRadius,'border-left-color':obj.color});break; 22 case 'bottom':$tail.css({'bottom':doubleRadius,'border-top-color':obj.color});break; 23 case 'left':$tail.css({'left':doubleRadius,'border-right-color':obj.color});break; 24 default:console.error('parameters given to function createBubble is not correct!'); 25 } 26 if(obj.left && (obj.tailPosition == 'bottom' || obj.tailPosition == 'top')){ 27 $tail.css('left',obj.left); 28 } 29 else if(obj.bottom && (obj.tailPosition == 'left' || obj.tailPosition == 'right')){ 30 $tail.css('bottom',obj.bottom); 31 } 32 else{ 33 console.error('Parameters are not correct!'); 34 } 35 if(obj.isShadow){ 36 $(v).hover(function(){ 37 $(v).css('box-shadow','2px 2px 5px #888888'); 38 },function(){ 39 $(v).css("box-shadow","none"); 40 }); 41 } 42 }); 43 }; 44 45 //parameters that obj should contain 46 // var obj = { 47 // width:'100px', 48 // height:'80px', size of the bubble 49 // isShadow:true, whether shadow or not 50 // color:'#09F', color of the bubble 51 // radius:'10px', bubble's border-radius property 52 // tailPosition:'right', position of the tail 53 // bottom:'80px', when tailPosition = 'left' or 'right' 54 // left:'100px', when tailPosition = 'top' or 'bottom' 55 // tailSize:'10px' size of the tail 56 // };
其中的注釋已經詳細的說明了配置的內容。星號(*)代表必填項。
實際使用如下:

HTML代碼

JavaScript代碼

效果圖
其他效果:



在大量使用到氣泡的場景,引入這個函數還是非常省心的。不過在使用該函數之前記得引用jQuery。
該函數代碼已被放在我的GitHub上了,歡迎大家更新改進或者克隆。
