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];
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章