1. 程式人生 > >YUI介紹以及快速入門 Yahoo的JS框架

YUI介紹以及快速入門 Yahoo的JS框架

1、YUI介紹:

YUI庫是一系列使用Javascript和CSS建立的的工具和控制元件集,用來建立富客戶端Web應用。使用到了DOM scripting,DHTML和AJAX。

2、在頁面中引入JS檔案:

可以從官網下載YUI http://yuilibrary.com/yui/quick-start/ 然後引入頁面,也可以線上引入

<script type="text/javascript" src="script/yui3/build/yui/yui-min.js"></script>
<!-- <script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script> -->
3、開始使用YUI: 3.1、建立一個YUI沙箱:
<script>
// Create a YUI sandbox on your page.
YUI().use('node', 'event', function (Y) {
    // The Node and Event modules are loaded and ready to use.
    // Your code goes here!
});
</script>

建立一個YUI例項用於使用所有的YUI組建,也叫一個沙箱。每一個YUI沙箱都有它自己的一個例項和一套自己的激活了的模組,所以它不會與同一個頁面中的其他沙箱衝突。任何定義在沙箱內的變數只會在本沙箱內有效,不會自動變成全域性變數。

當宣告一個沙箱 時,指定你想想要使用的模組,在上面的程式碼中,我們指定了使用node和even模組 。這樣,我們就可以在這個沙箱內通過Y來使用node和evnet的API了。

YUI會管理需要依賴的各模組的運算和載入在你的頁面中單一請求或者組合請求中需要使用到得JS檔案。在所有的YUI模組載入完成後你的程式碼將會被執行。

3.2、在YUI中使用DOM節點

YUI中的節點元件使得使用,建立和操作DOM節點變得非常方便。節點API允許使用元素相關參照物或者選擇器去使用DOM決節點

<script>
YUI().use('node', function (Y) {
    // Access DOM nodes.
var oneElementById = Y.one('#foo'), oneElementByName = Y.one('body'), allElementsByClass = Y.all('.bar'); // Create DOM nodes. var contentNode = Y.Node.create('<div>'), listNode = Y.Node.create('<ul>'), footerNode = Y.Node.create('<footer>'); contentNode.setContent('<p>Node makes it easy to add content.</p>'); listNode.insert('<li>Buy milk</li>'); footerNode.prepend('<h2>Footer Content</h2>'); // Manipulate DOM nodes. Y.all('.important').addClass('highlight'); Y.one('#close-button').on('click', function () { contentNode.hide(); }); }); </script>
3.3、建立UI效果

使用Transition元件使得在你的使用者互動中建立基於CSS的絢麗效果變得更加容易了。

<script>
YUI().use('transition', function (Y) {
    // Fade away.
    Y.one('#fademe').transition({
        duration: 1, // seconds
        opacity : 0
    });

    // Shrink to nothing.
    Y.one('#shrinkme').transition({
        duration: 1, // seconds
        width   : 0,
        height  : 0
    });
});
</script>
3.4、使用Ajax載入內容

由node-load模組提供的Node.load()方法使得在頁面執行時動態的新增內容更方便了。

<script>
YUI().use('node-load', function (Y) {
    // Replace the contents of the #content node with content.html.
    Y.one('#content').load('content.html');
});
</script>