Abstract
在使用markdown
編輯器寫博客的時候,發現了這個提示框很好看,如下圖:
- 圖一:帶箭頭提示框圖
- 圖二:普通提示框
下面就來依次實現一下。
2. Related Data
在參考一的文章中介紹了CSS實現帶箭頭的提示框
[1]。箭頭的設計在這裏其實有三種可行方案:
- 考慮使用圖片作爲頂部的三角的背景;
- 考慮使用
SVG
來繪製頂部的三角圖形; - 純粹的依靠
CSS
的border
屬性來設置,無疑是很好的一種方式;
因爲,自己之前也沒有接觸過使用border-color
來指定顏色,故而這裏來記錄一下。
3. Experiment
先定義結構:
<div class="info-type-one">
<!-- 內容區域 -->
<div class="">
測試內容!
</div>
<!-- 顯示提示區域 內容 -->
<div class="info-panel-content">
<!-- 顯示提示框區域 三角區域 -->
<div class="info-panel-triple"></div>
你好!
</div>
</div>
然後定義樣式:
<style type="text/css">
.info-type-one{
width: 120px;
height: 30px;
border: 1px solid #EEE;
margin: 0 auto;
text-align: center;
line-height: 30px;
}
.info-panel-triple{
width: 0;
height: 0;
border: 8px solid transparent;
border-bottom-color: hsla(0,0%,6%,.6);
position: absolute;
left: 16px;
top: -16px;
}
.info-panel-content{
display: inline-block;
position: relative;
margin-top: 15px;
height: 30px;
line-height: 30px;
background-color: hsla(0,0%,6%,.6);
color: #FFF;
text-align: left;
padding-left: 15px;
padding-right: 12px;
border-radius: 3px;
font-size: 0.8rem;
letter-spacing: 0.1rem;
}
</style>
很容易就可以看見表現:
當然,我們也可以用js
代碼來封裝一下,以簡化調用。
封裝:
首先還是微調一下CSS
的樣式代碼:
.info-panel-type-one{
position: absolute;
}
.info-panel-triple{
width: 0;
height: 0;
border: 8px solid transparent;
border-bottom-color: hsla(0,0%,6%,.6);
position: absolute;
left: 16px;
top: -16px;
}
.info-panel-content{
display: inline-block;
position: relative;
margin-top: 15px;
height: 30px;
line-height: 30px;
background-color: hsla(0,0%,6%,.6);
color: #FFF;
text-align: left;
padding-left: 15px;
padding-right: 12px;
border-radius: 3px;
font-size: 0.8rem;
letter-spacing: 0.1rem;
user-select: none;
-ms-user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
cursor: pointer;
}
然後編寫對應的js
代碼:
/**
* 創建提示框的第一種類型
* @param {Object} parent 父控件
* @param {Object} content 提示內容
*/
function create_info_panel_type_one(parent, content){
var info_panel = document.createElement('div');
info_panel.className = 'info-panel-type-one';
var conent_panel = document.createElement('div');
conent_panel.className = 'info-panel-content';
var triple_panel = document.createElement('div');
triple_panel.className = 'info-panel-triple';
conent_panel.innerText = content;
conent_panel.appendChild(triple_panel);
info_panel.appendChild(conent_panel);
parent.append(info_panel);
}
測試:
頁面代碼:
<div class="hello" style="width: 200px;margin: 80px auto;">
這裏是測試的塊1。
</div>
<div class="hello" style="width: 200px;margin: 80px auto;">
這裏是測試的塊2。
</div>
<script type="text/javascript">
// 調用
var info_list = ["Hello world!", 'Tom']
var info_panel_type_one_list = document.getElementsByClassName('hello');
for(var i=0;i<info_panel_type_one_list.length;i++){
// 處理一下閉包
(function (i){
var item = info_panel_type_one_list[i];
create_info_panel_type_one(item, info_list[i]);
})(i);
}
</script>
就可以很容易看見效果:
至於第二個那個比較簡單的提示,這裏就不寫了。嘿嘿。
參考文章:
[1] CSS實現帶箭頭的提示框