Web開發中9個有用的提示和技巧

oschina發表於2012-09-08

  在本文中,我們給出 9 個有用的 HTML、CSS 和 JavaScript 的技巧和提示,可能在做 Web 開發中經常會需要用到的,其中有幾個是關於 HTML5 和 CSS3 的,如果你是一個前端開發者,那麼或許對你有些用處。

tips and tricks

1. 使用 html5 的 placeholder 屬性

  以前我們經常要寫不少JavaScript 的程式碼來實現現在HTML5 的 placeholder 屬性的功能,一個輸入框在沒獲取焦點時顯示某個提示資訊,當獲得輸入焦點就自動清除提示資訊,目前支援該屬性的瀏覽器有:Opera 11+, Firefox 9+, Safari 5+, IE 10+,不過下面提供的程式碼對於不支援 placeholder 的瀏覽器也適用:

// jQuery code
var i = document.createElement("input");
 
// Only bind if placeholder isn't natively supported by the browser
if (!("placeholder" in i)) {
    $("input[placeholder]").each(function () {
        var self = $(this);
        self.val(self.attr("placeholder")).bind({
            focus: function () {
                if (self.val() === self.attr("placeholder")) {
                    self.val("");
                }
            },
            blur: function () {
                var label = self.attr("placeholder");
                if (label && self.val() === "") {
                    self.val(label);
                }
            }
        });
    });
}
 
<!-- html5 -->
<input type="text" name="search" placeholder="Search" value="">

2. 使用 font face

  你可以通過 font face 來使用一些更好的獨特的字型,支援多數瀏覽器:Opera 11+, Firefox 3+, Safari 5, IE6+

@font-face {
    font-family: 'MyWebFont';
    src: url('webfont.eot'); /* IE9 Compat Modes */
    src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('webfont.woff') format('woff'), /* Modern Browsers */
         url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
    }
     
body {
       font-family: 'MyWebFont', Fallback, sans-serif;
}   

3. Box Sizing

  好吧,我會說這是我最近最喜歡的CSS屬性。它可以解決佈局問題。例如,當您新增一個textfield填充,寬度將是文字框的寬度+填充,這很煩人,它通常將打破布局。然而,通過使用這個屬性,它解決了這個問題。

 支援的瀏覽器:Opera 8.5+, Firefox 1+, Safari 3, IE8+, Chrome 4+

textarea {
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
}

4. 禁用 Textarea 的大小改變

  有些時候你不需要使用者可以改變多行文字輸入口 textarea 的大小,可是一些基於 Webkit 的瀏覽器(例如 safari 和 chrome)就可以讓使用者隨意更改 textarea 大小,好在你可以禁用這個特性:

textarea {
    resize: none
}

5.jQuery.trim()

  用來去除字串前後的空格:

$.trim("       a lot of white spaces, front and back!      ");

6. jQuery.inArray()

  用來判斷某個元素是否在陣列之中:

var arr = [ "xml", "html", "css", "js" ];
$.inArray("js", arr);

 

7. 編寫一個簡單的 jQuery 外掛(模板)

//You need an anonymous function to wrap around your function to avoid conflict
(function($){
  
    //Attach this new method to jQuery
    $.fn.extend({
          
        //This is where you write your plugin's name
        pluginname: function() {
  
            //options
            var defaults = {
                option1: "default_value"
            }
             
            var options = $.extend(defaults, options);
  
            //a public method
            this.methodName: function () {
                //call this method via $.pluginname().methodName();
            }
  
            //Iterate over the current set of matched elements
            return this.each(function() {
              
                var o = options;
              
                //code to be inserted here
              
            });
        }
    });
      
//pass jQuery to the function,
//So that we will able to use any valid Javascript variable name
//to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )      
})(jQuery);

8. 擴充套件 jQuery 選擇器的功能

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^s+|s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}
 
/******** Usage ********/
 
// Select all elements with an ID starting a vowel:
$(':regex(id,^[aeiou])');
  
// Select all DIVs with classes that contain numbers:
$('div:regex(class,[0-9])');
  
// Select all SCRIPT tags with a SRC containing jQuery:
$('script:regex(src,jQuery)');

9. 優化並降低 PNG 影像檔案的大小

  你可以通過降低顏色數來降低png檔案的大小,詳情請看 PNG file optimization

結論

  前端開發是一個非常有趣的領域,我們永遠不能能學到一切。每次我工作的一個新專案,我總是覺得自己發現一些新的或奇怪的東西。我覺得這幾個技巧,將是非常方便和有用的;)

英文原文:9-useful-tips-and-tricks-for-web-developers

相關文章