2017年6月17日 星期六

PrimeFaces p:calendar 元件套用 bootstrap form-control 樣式

技術問題

PrimeFaces p:calendar 套用 bootstrap .form-control 是無法正確顯示。p:calendar 的輸入外框會超出元件邊界外框,如下圖所示:



分析與解決
p:calendar render 的結果會產生:

<span>
<input type="text" />
</span>

如果對 p:calendar 套用 .form-control,其結果會如下所示,.form-control 被套用在 <span> 上,而不是 <span> 內的 <input>

另外,<input> 的寬度不會自動響應,為固定寬度。


解決方式
1. 使用 jQuery Document Ready 時套用 .form-control <span> 內的 <input> 內。

$(function(){
    $('.ui-calendar > input').addClass('form-control');
});

2. 修改 .ui-inputfield width 屬性為 100%.

成果
程式碼
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/>
<style>
.ui-inputfield {
width: 100%;
}
</style>
</h:head>
<h:body>
<h1>PrimeFace p:calendar</h1>
<h:form class="form-horizontal">
<div class="form-group">
<div class="col-lg-5">
<p:calendar />
</div>
</div>
</h:form>
<h1>PrimeFace p:calendar with bootstrap</h1>
<h:form class="form-horizontal">
<div class="form-group">
<div class="col-lg-3">
<div class="input-group">
<p:calendar />
<span class="input-group-addon">Text</span>
</div>
</div>
</div>
</h:form>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script>
$(function(){
$('.ui-calendar > input').addClass('form-control') ;
});
</script>
</h:body>
</html>
view raw index.xhtml hosted with ❤ by GitHub
參考資料
[1] Primefaces style is applied on <span> instead of <input>
, https://stackoverflow.com/questions/16299635/primefaces-style-is-applied-on-span-instead-of-input


沒有留言: