2013/07/19

float元素生成順序的差異

用下面的html,我預期得到左右各有一個button(float div),剩下空間是status bar(div)
結果卻會是:
<div>
    <div class="pull-left btn">Button</div>    
    <div class="alert alert-info">Status bar</div>
    <div class="pull-right btn">Button</div>    
</div>
Button
Status bar
Button


這是由於第二個div在生成的時候就先將其父元素剩下的空間填滿了(block元素的特性)
第三個float div則被擠到了下面

所以將生成順序調整一下,讓float div先生成,這樣就不會被擠下去了
<div>
    <div class="pull-left btn">Button</div>    
    <div class="pull-right btn">Button</div>
    <div class="alert alert-info">Status bar</div>
</div>
Button
Button
Status bar


不過div的背景依舊會填滿父元素的空間,只有content會跟著float元素排版
此時CSS加上overflow,設成hidden或auto就可以正確的調整背景大小到float元素占據後剩下的空間了
<div>
    <div class="pull-left btn">Button</div>    
    <div class="pull-right btn">Button</div>
    <div class="alert alert-info" style="overflow:hidden;">Status bar</div>
</div>
Button
Button
Status bar


延伸閱讀:
All about floats

文字顯示過長時以省略符號顯示並提示完整文字

此CSS只作用於單行文字的顯示上
.text-overflow-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

為了達到只在過長被省略才顯示提示,需要用javascript判斷一下 (這邊以jQuery為例)
$(function() {
    $('.text-overflow-ellipsis').each(function() {
        if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
            $(this).attr('title', $(this).text());
        }
    });
});

2013/07/17

取得瀏覽器顯示的Scrollbar寬度


有些情況下,需要取得Scrollbar寬度來動態計算元件長寬
參考了一下網路上的作法,用jQuery寫了一個function來做這件事
/**
 * 1. Generate nested divs
 * 2. Calculate the width of inner div before and after scrollbar becomes visible.
 * @returns calculated scrollbar width
 */
function getScrollbarWidth() {
    var $tempNode = 
        $('<div/>')
            .css({
                width: 100,
                position: 'absolute',
                top: -1000
            })
            .append($('<div/>', { height: 100 }))
            .appendTo('body');
 
    var withoutSroll = $tempNode.children(':first').innerWidth();
    var withScroll = $tempNode.css({ 'overflow-y': 'scroll' })
                        .children(':first').innerWidth();

    $tempNode.remove();
    return withoutSroll - withScroll;
}

Backbone.js 雜記

版本1.0.0
  • extend Backbone.View 時傳入的參數:events,格式
    {'event selector': 'callback'}
    底層使用 jQuery.on(event, selector, callback) 來完成事件註冊,要注意的是如果 selector 有值,根據 jQuery api 這事件只會發生在根 DOM 下符合 selector 條件的子 DOM 上。
    When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector.
  • Backbone的View與Model要達到資料與顯示同步,得自行從View用listenTo()對Model的資料變動時的事件作處理