No3 jQuery

一 JS實現瀑布流

  • 搭建HTML結構
<body>
    <!--父標籤-->
    <div id="pall">
        <!--盒子-->
        <div class="box">
            <div class="pic">
                <img src="images/0.jpg">
            </div>
        </div>
        <div class="box">
            <div class="pic">
                <img src="images/1.jpg">
            </div>
        </div>
        <div class="box">
            <div class="pic">
                <img src="images/2.jpg">
            </div>
        </div>
        ……  ……
</body>      
  • css 樣式
a, address, b, big, blockquote, body, center, cite, code, dd, del, div, dl, dt, em, fieldset, font, form, h1, h2, h3, h4, h5, h6, html, i, iframe, img, ins, label, legend, li, ol, p, pre, small, span, strong, u, ul, var{
    padding: 0;
    margin: 0;
}

#pall{
    position: relative;
}

#pall .box{
    padding-top: 15px;
    padding-left: 15px;
    float: left;
    /*background-color: red;*/
}

#pall .box .pic{
    padding: 10px;
    border: 1px solid #ddd;
    box-shadow: 0 0 2px #ddd;
    border-radius: 5px;
    width: 165px;
}

#pall .box .pic img{
    width: 165px;
}
  • js 文件
function $(id){
   return typeof  id === 'string' ? document.getElementById(id):id;
}

//當頁面加載完畢
window.onload = function(){
    // 實現瀑布流
    waterFall('pall', 'box');
    // 當屏幕滾動
    window.onscroll = function(){
       // 滿足條件
        if(checkWillScroll()){
//            alert(0);
            // 造數據
            var dataImg = {'img':[{'src':'0.jpg'},{'src':'5.jpg'},{'src':'8.jpg'},{'src':'9.jpg'},{'src':'2.jpg'}]};
           // 創建標籤
            for(var i=0; i<dataImg.img.length; i++){
                // 造div
                var newBox = document.createElement('div');
                newBox.className = 'box';
                $('pall').appendChild(newBox);

                var newPic = document.createElement('div');
                newPic.className = 'pic';
                newBox.appendChild(newPic);

                var newImg = document.createElement('img');
                newImg.src = 'images/' + dataImg.img[i].src;
                newPic.appendChild(newImg);
            }
            waterFall('pall', 'box');
        }
    }
}
// 實現瀑布流佈局
function waterFall(parent, box){

    // 拿到所有的盒子
    var allBox = $(parent).getElementsByClassName('box');
    // 取出其中一個盒子的寬度
    var boxWidth = allBox[0].offsetWidth;
    // 取出瀏覽器的寬度
    var clientWidth = document.body.clientWidth;
    // 求出列數
    var cols = Math.floor(clientWidth / boxWidth);
    // 讓父標籤居中
    $(parent).style.cssText = 'width:' + cols * boxWidth + 'px; margin:0 auto';

    //定位
    var heightArr = [];
    // 遍歷所有的盒子
    for(var i=0; i<allBox.length; i++){
        // 求出每一個盒子的高度
        var boxHeight = allBox[i].offsetHeight;
        if(i<cols){ // 第一行
            heightArr.push(boxHeight);
        }else{ // 剩餘的行
            // 取出最矮盒子的高度
            var minBoxHeight = Math.min.apply(null, heightArr);
            // 取出最矮盒子對應的索引
            var minBoxIndex = getMinIndex(minBoxHeight, heightArr);
            // 剩餘盒子定位
            allBox[i].style.position = 'absolute';
            allBox[i].style.top = minBoxHeight +'px';
            allBox[i].style.left = minBoxIndex * boxWidth +'px';
            // 更新數組的高度
            heightArr[minBoxIndex] += boxHeight;
        }
    }
    //    console.log(heightArr, minBoxHeight, minBoxIndex);
}

// 取出最矮盒子對應的索引
function getMinIndex(value, arr){
    for(var i=0; i< arr.length; i++){
        if(value == arr[i]){
            return i;
        }
    }
}
// 檢查是否滿足條件
function checkWillScroll(){
    // 取出所有的盒子
    var allBox = $('pall').getElementsByClassName('box');
    // 取出最後一個盒子
    var lastBox = allBox[allBox.length -1];
    // 取出最後一個盒子高度的一半 + 頭部偏離的位置
    var lastBoxDis = Math.floor(lastBox.offsetHeight / 2)  + lastBox.offsetTop;
    // 求出瀏覽器的高度
    var clientHeight = document.body.clientHeight || document.documentElement.clientHeight;
    // 求出頁面偏離瀏覽器的高度
    var offsetTop = document.body.scrollTop;

//    console.log(lastBoxDis, clientHeight, offsetTop);

    return lastBoxDis < (clientHeight + offsetTop) ? true :false;

}
  • 用css3實現瀑布流佈局(一行代碼搞定)
    • 多欄佈局
#pall{
    /*position: relative;*/

    -webkit-column-width: 202px;
    -moz-column-width: 202px;
    column-width: 202px;
}

二 jQuery

  • JQuery是繼prototype之後又一個優秀的Javascript庫。它是輕量級的js庫 ,它兼容CSS3,還兼容各種瀏覽器…

    • jQuery是一個兼容多瀏覽器的javascript庫,核心理念是write less,do more(寫得更少,做得更多)。
  • jQuery特點:

    • 1.輕鬆DOM的操作
    • 2.幾乎沒有兼容問題
    • 3.輕鬆實現動畫
  • jQuery代碼示例
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">

    // 拿到標籤
//    alert($('img'));
    // 查看屬性
//    console.log($('img').attr('width'));
    // 改變屬性值
    $('img').attr('src', 'image/img_02.jpg');
    $('img').attr('width', '100');

    // 改變標籤中內容
    console.log($('#main>p').text());
    $('#main>p').text('xxx');

    // 顯示 和 隱藏
    $('button').eq(0).on('click', function(){
        $('#main>p').show();
        $('img').show();
    });

    $('button').eq(1).on('click', function(){
        $('#main>p').hide();
        $('img').hide();
    });
    // toggle 切換
    $('button').eq(2).on('click', function(){
        $('#main>p').toggle(2000);
        $('img').toggle(2000);
    });

    var data = [10,2332,4343,56,76,8787];
    // 遍歷
    $.each(data, function(index, value){
        console.log(index, value);
    });
    // 取出某值對應的索引
   var index =  $.inArray(56, data);
   alert(index);

// 用jQuery寫 css 樣式
$('#main').css({
        'background' : 'red',
        'width' : '550px',
        'height' : '330px'
    });

三 用jQuery實現瀑布流佈局

// 當頁面加載完畢
$(window).on('load', function(){
    // 實現瀑布流佈局
    waterFall();
    // 監聽鼠標的滾動
    $(window).on('scroll', function(){
       //判斷是否具備滾動條件
        if(checkWillScroll()){
           // 造數據
            var dataImg = {'img':[{'src':'images/0.jpg'},{'src':'images/8.jpg'},{'src':'images/10.jpg'},{'src':'images/11.jpg'},{'src':'images/5.jpg'},{'src':'images/7.jpg'}] };
           // 遍歷
            $.each(dataImg.img, function(index, value){
                // 創建新的盒子
                var newBox = $('<div>').addClass('box').appendTo($('#pall'));
                var newPic = $('<div>').addClass('pic').appendTo($(newBox));
                $('<img>').attr('src', $(value).attr('src')).appendTo($(newPic));
            });
            // 實現瀑布流佈局
            waterFall();
        }
    });
});
// 實現瀑布流佈局
 function waterFall(){
     // 拿到所有的盒子
     var allBox = $('#pall>.box');
     // 求出盒子的寬度
     var boxWidth = $(allBox).eq(0).outerWidth();
     // 求出瀏覽器的寬度
     var clientWidth = $(window).width();
     // 求出列數
     var cols = Math.floor(clientWidth / boxWidth);
     // 讓父標籤居中
     $('#pall').css({
         'width' : boxWidth * cols + 'px',
         'margin' : '0 auto'
     });

     // 定位
     var heightArr = [];
     // 遍歷所有的盒子
     $.each(allBox, function(index, value){
         // 取出盒子的高度
         var boxHeight = $(value).outerHeight();
         if(index < cols){ // 第一行
            heightArr[index] = boxHeight;
         }else{// 剩餘的行
            // 求出數組中最矮盒子的高度
             var minBoxHeight = Math.min.apply(null, heightArr);
            // 求出最矮盒子對應的索引
             var minBoxIndex = $.inArray(minBoxHeight, heightArr);
            // 定位
             $(value).css({
                 'position' : 'absolute',
                 'top' : minBoxHeight + 'px',
                 'left' : minBoxIndex * boxWidth + 'px'
             })
             // 更新高度
             heightArr[minBoxIndex] += boxHeight;
         }

     });
 }
// 判斷是否具備滾動條件
function checkWillScroll(){
    // 拿到最後一個盒子
    var lastBox = $('#pall>.box').last();
    // 求出最後盒子高度的一半 + 頭部偏離的位置
    var lastBoxDis = Math.floor($(lastBox).outerHeight() / 2) + $(lastBox).offset().top;
    // 求出瀏覽器的高度
    var clientHeiht = $(window).height();
    // 求出頁面偏離瀏覽器的高度
    var scrollTop = $(window).scrollTop();
    // 判斷
    return lastBoxDis < (clientHeiht + scrollTop) ? true : false;
}

四 bootstrap快速開發

  • 導航條

    • 添加 .navbar-fixed-top 類可以讓導航條固定在頂部
      • 注意:固定的導航條會遮住頁面上的其他內容,可給<body>設置 padding
    • 包含一個.container或.container-fluid容器,從而讓導航條居中顯示或者自適應顯示
    • 添加.navbar-inverse可以改變導航欄顯示的背景顏色
  • 一個典型的柵格系統佈局

<div class=“container”>
    <div class=“row”>
        <div class=“col-md-4”>.col-md-4</div>
       <div class=“col-md-4”>.col-md-4</div>
       <div class=“col-md-4”>.col-md-4</div>
    </div>
</div>
  • 行(row)必須包含在.container(固定寬度)或.container-fluid(100%)中
  • 使用.col-md-*柵格類,就可以創建一個基本的柵格系統,在手機和平板設備一開始是堆疊在一起,在屏幕(>970px)的設備上水平排列

  • 交叉佈局

    • 通過使用針對平板設備的 .col-md-* 類,可以創建更加動態和強大的佈局:
 <div class="row">
   <div class=“col-md-7”>.col-md-7</div>
   <div class=“col-md-5”>.col-md-5</div>
 </div>
  • 標籤頁 Tabs

    • 標籤頁是一個經常使用的組件,可以放置很多的內容,最大亮點是:節省頁面空間

    這裏寫圖片描述

  • Tab切換代碼實現

$('#myTabs a[href="#profile"]').tab('show') // Select tab by name
$('#myTabs a:first').tab('show') // Select first tab
$('#myTabs a:last').tab('show') // Select last tab
$('#myTabs li:eq(2) a').tab('show') // Select third tab (0-indexed)
  • 模態框

這裏寫圖片描述

<div class="modal fade" id="about-modal" tabindex="-1" role="dialog" aria-labelledby="modal-label" aria-hidden="true" style="display: none;">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">Modal title</h4>
                </div>
                <div class="modal-body">
                    <p>One fine body&hellip;</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

五 OC 調用 HTML

  • 拖一個 webview,遵守代理協議
@interface ViewController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (nonatomic, weak)  UIActivityIndicatorView *displayView;
@end
  • 配置 info.plist

    • iOS9裏面要求網絡請求使用安全協議

    這裏寫圖片描述

- (void)viewDidLoad {
    [super viewDidLoad];

    // 加載網頁
    NSURL *url = [NSURL URLWithString:@"http://www.xianhua.cn/m/"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];

    self.webView.scrollView.hidden = YES;
    self.webView.backgroundColor = [UIColor grayColor];

    UIActivityIndicatorView *displayView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; // 轉菊花效果
    [displayView startAnimating];
    self.displayView = displayView;
    displayView.center = self.view.center;
    [self.webView addSubview:displayView];
}
  • 代理方法,修改頁面
#pragma mark -<UIWebViewDelegate>
- (void)webViewDidFinishLoad:(UIWebView *)webView{

    // 改變標題
    NSString *str = @"document.getElementsByTagName('h1')[0].innerText = '鮮花網';";
    [webView stringByEvaluatingJavaScriptFromString:str];

    // 刪除廣告
    NSString *str2 =@"document.getElementsByClassName('detail_btns2')[0].remove();";
    [webView stringByEvaluatingJavaScriptFromString:str2];

    // 改變尾部
    NSString *str3 = @"document.getElementById('xiazaiapp').getElementsByTagName('a')[0].innerText='下載鮮花網App';";
    [webView stringByEvaluatingJavaScriptFromString:str3];
 // 模仿網絡加載慢時加載過程   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.webView.scrollView.hidden = NO;
        [self.displayView stopAnimating];
    });

}

六 HTML 調用 OC

  • html 文件
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        body{
            margin-top: 50px;
        }
    </style>
</head>
<body>
    <button onclick="openCamera();">訪問相冊</button>
    <script type="text/javascript">
        function openCamera(){
            window.location.href = 'ds3q:///openCamera';
        }
    </script>
</body>
</html>
  • 加載 html(webview)
- (void)viewDidLoad {
    [super viewDidLoad];

    // 加載網頁
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}
  • 打開相冊需要用到 webview 的代理
#pragma mark - <UIWebViewDelegate>
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    NSLog(@"------%@", request.URL.absoluteString);
    NSString *requestUrl = request.URL.absoluteString;
    NSRange range = [requestUrl rangeOfString:@"ds3q:///"];
    NSUInteger location = range.location;
    if (location != NSNotFound) { // 找到了對應協議頭
        NSString *str = [requestUrl substringFromIndex:location + range.length];
        NSLog(@"%@", str); // 輸出 openCamera
        // 包裝SEL
        SEL method = NSSelectorFromString(str);
        [self performSelector:method];
    }  
    return YES;
}
  • 實現打開相冊功能
- (void)openCamera{
    UIImagePickerController *vc = [[UIImagePickerController alloc] init];
    vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:vc animated:YES completion:nil];
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章