2015年7月27日 星期一

[JS] jQuery 顯示 badge

badge 就是一個小圈圈裡有數字,找到一個有趣的 sample code, 可以下一個 class 就套出 badge, 缺點就是需要調一下別人的 css 把 沒有在用 style 先拿掉。

套出來的畫面:

使用方法:
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Badges on Buttons</h2>
  <button type="button" class="btn btn-primary">Primary <span class="badge">7</span></button>
  <button type="button" class="btn btn-success">Success <span class="badge">3</span></button>    
  <button type="button" class="btn btn-danger">Danger <span class="badge">5</span></button>        
</div>

</body>
</html>



example 2:
<!DOCTYPE html>
<html>

<head>
    <link data-require="bootstrap@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
    <script data-require="jquery@*" data-semver="2.1.3" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
</head>

<body>
    <button class="btn btn-sm btn-default like-btn active" type="button" id="10">
        <span class="glyphicon glyphicon-thumbs-up"></span>
        <span class="text">Liked</span>
        <span class="badge like-badge">1</span>
    </button>
    <script>
        $(document).on("click", ".like-btn", function(e) {
            e.preventDefault();

            var $label = $(this).find('.text'),
                $badge = $(this).find('.badge'),
                count = Number($badge.text()),
                active = $(this).hasClass('active');

            $label.text(active ? 'Like' : 'Liked');
            $badge.text(active ? count - 1 : count + 1);
            $(this).toggleClass('active');
        });
    </script>
</body>
</html>


資料來源:
http://www.w3schools.com/bootstrap/bootstrap_badges_labels.asp


2014年10月3日 星期五

[JS] Sweet Alert

我覺得每個網站都應該用這一個SweetAlert套件來做, 最好再改一下 UI sytle, 配合該網站的  style, 雖然已經有很多 jQuery 做出類似的功能, 看了一下SweetAlert用法和安裝方法, 真是簡單到爆, SweetAlert 和預設醜死的javascript alert的視窗相比,SweetAlert 在 UI 上顯示出來就漂亮許多,在功能面還加強了許多功能.

官方網站: http://tristanedwards.me/sweetalert
github: https://github.com/t4t5/sweetalert




2014年10月2日 星期四

[CSS] use image-set to support retina images

一般解析度的圖片在 retina 下其實不太漂亮, 在 retina 顯示下可以顯示更高的解析度圖片, 透過css 增加 image-set 可以user 在 使用 retina 瀏覽時使用較高解析度的圖片.

雖然目前只支援 background-image 屬性,而不能使用在 <img> tag 裡, 我覺得這個問題還滿容易解決的, 使用一個 <div> tag 加 class 後, 就可以長的像 <img> tag 了, 只是<div> tag 右邊的區塊預設會折行, 需要手動設一下 float:left;, 然後會有區塊右邊文字置頂的問題, 這個用css 也都很好解決, 設個 padding 或再使用一個 div  position:absolute; 再配合坐標; 應該就ok了.
<== 由於我不太懂 css, 這部份可能有誤.


在 retina 下的顯示實測:
可以清楚看的出來第1張圖糊糊的, 第2張圖(高解析度)就銳利很多.




相同的 html 在 PC 裡執行:
只有下載低解析度的版本.


解法1:

Serving Images Efficiently to Displays of Varying Pixel Density
https://developer.apple.com/library/safari/documentation/NetworkingInternet/Conceptual/SafariImageDeliveryBestPractices/ServingImagestoRetinaDisplays/ServingImagestoRetinaDisplays.html

header {
    background: -webkit-image-set( url(images/header.jpg)    1x,
                                   url(images/header_2x.jpg) 2x);
    height: 150px; /* height in CSS pixels */
    width: 800px; /* width in CSS pixels */
}

加個 -webkit-image-set 就做完了.

這個做法的優點是, client 端只會從 server side 下載指定大小的圖片, 對 client side 來說傳輸給顯示效果較好, 對 server side 來說, 由於多一個檔案, 所以需要 maintain 工作會多一點點, 所佔用的儲存空間多一點點, 但我覺得這個是利大於弊, 是可行的.

解法1在舊的瀏覽器不支援.


解法2:
直接放一張2倍解析度的大圖, 讓browser 自己 resize 到指定的寬和高, 這個作法更快, 相容性更高, 缺點是 client side 和解法1相比會慢一點點點(對使用者來說無感).

衷心地建議您, 如果都知道來源圖片的 pixel, Html 或 Css 裡請指明該圖片的 width + height, 只寫一個 width 是很方便沒錯, 但是在某些browser 或 eMail Client(ex: outlook)下畫面裡的圖片會為了 resize image 而"閃動", 視覺效果很差.

解法2在一些舊的瀏覽器(或eMail Reader)顯示效果會比較差, 因為他們對 image resize 的重新取樣(Resample)的處理"超差", 會有明顯的鋸齒/模糊或雜點.


結論:


  • 解法1在client side傳輸速度還是視覺效果可能比解法2好
  • 解法2在client side相容性和server side 改 css/html 實作的速度比解法1快.



相關文章:





2014年7月18日 星期五

[JS] html select 下拉框 顯示固定寬度

預設的 select box 的寬度會依照 option 裡的值(value) 長短而自動 resize 寬度, 在很多 select box 的畫面裡會不太好太, 解法有2:

  • 1. css (建議), min-width & max-width 屬性.
  • 2. javascript.

解法1:

Example

Set the minimum width of a paragraph:
p{
min-width:1000px;
}

Browser Support: ALL Browser


The min-width property is supported in all major browsers.
Note: IE6 and earlier versions do not support the min-width property.

html code:
<select name="Select1" style="min-width:100px; max-width:120px;">

執行畫面 (screent shot):


解法2: javascritp

執行畫面:


javascript source code:
==============
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
function FixWidth(selectObj)
{
    var newSelectObj = document.createElement("select");
    newSelectObj = selectObj.cloneNode(true);
    newSelectObj.selectedIndex = selectObj.selectedIndex;
    newSelectObj.onmouseover = null;
    var e = selectObj;
    var absTop = e.offsetTop;
    var absLeft = e.offsetLeft;
    while(e = e.offsetParent)
    {
        absTop += e.offsetTop;
        absLeft += e.offsetLeft;
    }
    with (newSelectObj.style)
    {
        position = "absolute";
        top = absTop + "px";
        left = absLeft + "px";
        width = "auto";
    }
    var rollback = function(){ RollbackWidth(selectObj, newSelectObj); };
    if(window.addEventListener)
    {
        newSelectObj.addEventListener("blur", rollback, false);
        newSelectObj.addEventListener("change", rollback, false);
    }
    else
    {
        newSelectObj.attachEvent("onblur", rollback);
        newSelectObj.attachEvent("onchange", rollback);
    }
    selectObj.style.visibility = "hidden";
    document.body.appendChild(newSelectObj);
    newSelectObj.focus();
}
function RollbackWidth(selectObj, newSelectObj)
{
    selectObj.selectedIndex = newSelectObj.selectedIndex;
    selectObj.style.visibility = "visible";
    document.body.removeChild(newSelectObj);
}
</script>
</head>
<body>
<form method="post">
    <div style="width:100px; height:100px; margin:100px; padding:10px; background:gray;">
        <select name="Select1" style="width:80px;" onmouseover="FixWidth(this)">
            <option id="A" title="this is A">AAAAAAAAAAAAAAA</option>
            <option id="B" title="this is B">BBBBBBBBBBBBBBB</option>
            <option id="C" title="this is C">CCCCCCCCCCCCCCC</option>
        </select>
    </div>
</form>
</body>
</html>

2014年7月11日 星期五

[JS] IE/FF/Chrome瀏覽器的複製到剪貼板功能

現在才知道 Safari 和 Chrome 無法透過javascript access clipboard., FireFox/IE 瀏覽器的語法:

function SetCopy()
{
var text = "hahaha\r\nbcd";
if (!CopyToClipboard(text)) {
return;
}
alert("已經把購買資訊複製到系統剪貼簿,您可以使用(Ctrl+V 或滑鼠右鍵)貼在留言欄位內。");
}

function CopyToClipboard(text) {
if (window.clipboardData) {
window.clipboardData.clearData();
window.clipboardData.setData("Text", text);
} else if (navigator.userAgent.indexOf("Opera") != -1) {
window.location = text;
} else if (window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
} catch (e) {
alert("被瀏覽器拒絕!\n請在瀏覽器地址欄輸入'about:config'並按上一頁\n然後將'signed.applets.codebase_principal_support'設置為'true'");
return false;
}
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if (!clip)
return false;
27: var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if (!trans)
return false;
trans.addDataFlavor('text/unicode');
32: var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
var copytext = text;
str.data = copytext;
trans.setTransferData("text/unicode", str, copytext.length*2);
var clipid = Components.interfaces.nsIClipboard;
if (!clip)
return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
44: return true;
}

若字串中有斷行,要使用「\r\n」。


要讓 chrome/safari 可以用的話, 只能透再包一層 flash 上去, 參考看看這2篇的作法:



 js 部分
<script type="text/javascript">
  var clipboardswfdata;
  var setcopy_gettext = function(){
    clipboardswfdata = document.getElementById('test_text').value;
    window.document.clipboardswf.SetVariable('str', clipboardswfdata);
  }
  var floatwin = function(){
    alert('複製成功!');
  }
</script>
這裡只寫到 Copy, 但沒有 demo past.

以下是 HTML 部分
<textarea id="test_text" rows="15" cols="100">文本內容</textarea>
<div id="clipboard_content">
  <div class="my_clip_button">
<span class="clipinner" id="clipinner">複製代碼到剪貼簿
    name="clipboardswf" class="clipboardswf" id="clipboardswf" onmouseover="setcopy_gettext()" devicefont="false" src="./_clipboard.swf" menu="false" allowscriptaccess="sameDomain" swliveconnect="true" wmode="transparent" type="application/x-shockwave-flash" height="20" width="100">
    </span>
  </div>
</div>
因為是用隱藏的 swf 覆蓋在 button 上面實現的
div id 和 span id 都不可改, swf 從 某貓痴的電腦學習筆記本 下載: http://it.nekounya.com/_php/catchbook/_clipboard.swf
=======================

改用 ZeroClipboard.swf 和 jquery.zclip.js 也很常見, 畢盡 desktop 的 browser 幾乎都支援 flash.




2013年10月21日 星期一

Cool Buttons 超連結變漂亮的按鈕

Wow, 好厲害,透過 <A> 超連結 tag 就做出各式各樣漂亮的 button,真的是太神奇了,立馬把 css 摳回家。

這裡有扁平設計(Flat Design)、漸變陰影 (Gradient)、3D 按鈕等一應俱全喔 (^_^)


URL: http://fribly.com/2013/10/18/cool-buttons/

2013年7月24日 星期三

Android 多國語系 strings.xml 檔案轉 iOS InfoPlist.strings

同時間開發 Android 和 iOS 時, 要共用其設定好的多國語言設定檔的話, 可以透過 Notepad++ 的 RegExp 來幫忙轉換.

Android to iOS:
Find: <string name="
([A-Z0-9_\-.%@ ':]+)">(.*)</string> 
Replace as: "\1"="\2";

iOS to Android:
Find: "([A-Z0-9_\-.%@ ':]+)"="(.*)";
Replace as: <string name="\1">\2</string>

Notepad++官方說明文章如下:

Notepad++ RegExp List
Note: In case you have the plugins installed, try CONTROL+R or in the Menu Plugins � TextFX Quick - Find/Replace to get a sophisticated dialogue including a drop down for regular expressions and multi line search/replace.
In a regular expression, special characters interpreted are:
.Matches any character
(This marks the start of a region for tagging a match; so what's inside ( ) you can use in "replace with" using \1, \2 etc.
)This marks the end of a tagged region.
\nWhere n is 1 through 9 refers to the first through ninth tagged region when replacing. For example, if the search string was Fred([1-9])XXX and the replace string was Sam\1YYY , when applied to Fred2XXX this would generate Sam2YYY .
\<This matches the start of a word using Scintilla's definitions of words.
\>This matches the end of a word using Scintilla's definition of words.
\xThis allows you to use a character x that would otherwise have a special meaning. For example, \[ would be interpreted as [ and not as the start of a character set.
[...]This indicates a set of characters, for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...]The complement of the characters in the set. For example, [^A-Za-z] means any character except an alphabetic character.
^This matches the start of a line (unless used inside a set, see above).
$This matches the end of a line.
*This matches 0 or more times. For example, Sa*m matches Sm , Sam , Saam , Saaam and so on.
+This matches 1 or more times. For example, Sa+m matches Sam , Saam , Saaam and so on.

Source of this information is the Scintilla edit component help, but it was adapted to Notepad++ behaviour.
Notepad++ RegExp Examples
Important
  • You have to check the box "regular expression" in search & replace dialog
  • When copying the strings out of here, pay close attention not to have additional spaces in front of them! Then the RegExp will not work!
You use a MediaWiki (e.g. WikipediaWikitravel) and want to make all headings one "level higher", so a H2 becomes a H1 etc.
  1. Search ^=(=)
    Replace with \1
    Click "Replace all" to find all headings2...9 (two equal sign characters are required) which begin at line beginning (^) and to replace the two equal sign characters by only the last of the two, so eleminating one and having one remaining.
  2. Search =(=)$
    Replace with \1
    Click "Replace all" to find all headings2...9 (two equal sign characters are required) which end at line ending ($) and to replace the two equal sign characters by only the last of the two, so eleminating one and having one remaining.
  3. == title == became = title =, you're done :-)
You have a document with a lot of dates, which are in German date format (dd.mm.yy) and you'd like to transform them to sortable format (yy-mm-dd). Don't be afraid by the length of the search term – it's long, but consiting of pretty easy and short parts.
  1. Search ([^0-9])([0123][0-9])\.([01][0-9])\.([0-9][0-9])([^0-9])
    Replace with \1\4-\3-\2\5
    Click "Replace all" to fetch
    • the day, whose first number can only be 0, 1, 2 or 3
    • the month, whose first number can only be 0 or 1
    • but only if the spearator is . and not any charcter ( . versus \. )
    • but only if no numbers are sourrounding the date, as then it might be an IP address instead of a date
    and to write all of this in the opposite order, except for the surroundings. Pay attention: Whatever SEARCH matches will be deleted and only replaced by the stuff in the REPLACE field, thus it is mandtory to have the surroundings in the REPLACE field as well!
  2. 31.12.97 became 97-12-31 and 14.08.05 became 05-08-14 and the IP address 14.13.14.14 did not change, you're done :-)
You have printed in windows a file list using dir /b/s >filelist.txt to the file filelist.txt and want to make local URLs out of them.
  1. Open filelist.txt with Notepad++
  2. Search \\
    Replace with /
    Click "Replace all" to change windows path separator char \  into URL path separator char / 
  3. Search ^(.*)$
    Replace with file:///\1
    Click "Replace all" to add file:/// in the beginning of all lines
  4. Depended on your requirements, preceed to escape some characters like space to %20 etc.
  5. C:\!\aktuell.csv became file:///C:/!/aktuell.csv, you're done :-)
Another Search Replace Example
[Data]
EU AX ALA 248 �land Islands
EU AL ALB 008 Albania, People's Socialist Republic of
AF DZ DZA 012 Algeria, People's Democratic Republic of
OC AS ASM 016 American Samoa
EU AD AND 020 Andorra, Principality of
AF AO AGO 024 Angola, Republic of
NA AI AIA 660 Anguilla
AN AQ ATA 010 Antarctica (the territory South of 60 deg S)
NA AG ATG 028 Antigua and Barbuda
SA AR ARG 032 Argentina, Argentine Republic
AS AM ARM 051 Armenia
NA AW ABW 533 Aruba
OC AU AUS 036 Australia, Commonwealth of
[SearchPattern]
([A-Z]+) ([A-Z]+) ([A-Z]+) ([0-9]+) (.*)
[ReplacePattern]
\1,\2,\3,\4,\5
[FinalData]
AS,AF,AFG,004,Afghanistan
EU,AX,ALA,248,�land Islands
EU,AL,ALB,008,Albania, People's Socialist Republic of
AF,DZ,DZA,012,Algeria, People's Democratic Republic of
OC,AS,ASM,016,American Samoa
EU,AD,AND,020,Andorra, Principality of
AF,AO,AGO,024,Angola, Republic of
NA,AI,AIA,660,Anguilla
AN,AQ,ATA,010,Antarctica (the territory South of 60 deg S)
NA,AG,ATG,028,Antigua and Barbuda
SA,AR,ARG,032,Argentina, Argentine Republic
AS,AM,ARM,051,Armenia
NA,AW,ABW,533,Aruba
OC,AU,AUS,036,Australia, Commonwealth of

Facebook 留言板