jq常用功能操作

 

//表示所有选中的商品
var $goods=$(".goods:checked");
var arr=[];
for(i=0;i<$goods.length;i++){
arr.push($goods.eq(i).id); //取出所有选中商品的id,这里是用eq(i)来读取选中的第几个元素!
}

$.ajax({
url:'login',
type:"post",
data:{id:arr},
success: function(res){

},
error: function(){
$.alert('出错啦!');
flag = true;
}
})

 

2、走马灯滚动

px单位的时候

方法一:

html:
<div class="list">
      <ul>
            <li></li>
             <li></li>
      </ul>
</div>



//滚动
$(function(){
     setInterval(function() {
      scrollList(".list");
     }, 3000);
});


    function scrollList(obj) {
        var parent = $(obj).find("ul");
        if(parent.find("li").length > 5) {
            parent.animate({  
                marginTop : "-1.05rem"  //单位可修改成px
            },800,function(){  
                parent.css({marginTop : "0"}).find("li:first").appendTo(this);  
            }) 
        }
    }

缺点:一直在进行dom操作,很耗性能,在有些页面下,ios滑动会出现闪屏!!!

方法二:

html:
 <div class="list" id="demo">
                <ul id="demo1">
                    <foreach name="none_list" item="vo" >
                        <li class="flexbox">
                            <div class="flexchild ellipsis">{$vo.nickname}</div>
                            <div class="flexchild">{$vo.join_num}</div>
                            <div class="flexchild ellipsis">{$vo.pro_name}</div>
                        </li>
                    </foreach>
                </ul>
                <ul id="demo2"></ul>
            </div>

js:
$(function(){
        var demo = document.getElementById("demo");
        var demo1 = document.getElementById("demo1");
        var demo2 = document.getElementById("demo2");
        var speed = 3000; //数值越大滚动速度越慢  
        demo2.innerHTML = demo1.innerHTML;

        demo.scrollTop = demo.scrollHeight + 'px';

        function Marquee() {
            if(demo2.offsetTop - demo.scrollTop <= 0) //当滚动至demo1与demo2交界时  
                $(demo).animate({
                    scrollTop: demo.scrollTop-demo1.offsetHeight
                }, 600);
            else {
                $(demo).animate({
                    scrollTop: demo.scrollTop + 53
                }, 800);
            }
        }
        if($("#demo1 li").length > 4) {
            setInterval(Marquee, speed);
        }

});

其中53为li的高度,li标签用直接设置高度,不要设置padding值撑开,不会滚动的时候,不会每次都滚动一条li值。

rem单位的时候js代码如下::

var demo = document.getElementById("demo");
    var demo1 = document.getElementById("demo1");
    var demo2 = document.getElementById("demo2");
    var speed = 3000; //数值越大滚动速度越慢  
    demo2.innerHTML = demo1.innerHTML;


    demo.scrollTop = demo.scrollHeight;
    demo.scrollTop = demo.scrollHeight;    
    function Marquee() {
        if(demo2.offsetTop - demo.scrollTop <= 0) //当滚动至              demo1与demo2交界时  
            $(demo).animate({
                scrollTop:0  //使用rem单位的时候
            }, 600);
        else {
            $(demo).animate({
                scrollTop:demo.scrollTop + window.innerWidth/750*105   //使用rem单位的时候进行适配
//                scrollTop: demo.scrollTop + 1.05 + "rem"
            }, 800);
            
            console.log(demo.scrollTop+"demo.scrollHeight"+ demo.scrollTop + window.innerWidth/750*105 )
        }
    }
    if($("#demo1 li").length > 5) {
        setInterval(Marquee, speed);
    }
    
    });    

 方法3

 

<div class="lunb-box">

<div class="lun-title">看大家的运气</div>

  <div class="lunb-list">
    <ul>
       <li class="flexbox flexbox-middle">
           <div class="photo"><img src="../../../Public/src/activity/2018/5yue1wan/images/photo.png?v={$v}" /></div>
           <div class="name ellipsis">昵称五个字你好么导航</div>
           <div class="time">3秒钟前</div>
           <div class="money">获得1.000元红包</div>
       </li>
   </ul>
 </div>
</div>

.lunb-box {
position: relative;
width: 7.5rem;
height: 5.5rem;
background: url("../images/lunb-bg.png") no-repeat;
background-size: 100% 100%;
margin-top: .18rem;
padding: 1rem .1rem .9rem .5rem;
box-sizing: border-box;
overflow: hidden;
font-size: .3rem;
}
.lunb-list {
height: 4.35rem;
overflow: hidden;

}
.lunb-list li {
height: .9rem;
}
.lunb-list .photo {
width:.6rem;
height: .6rem;
border-radius:50% ;
overflow: hidden;
}
.lunb-list .photo img {
width: 100%;
}
.lunb-list .name {
width:1.85rem;
margin:0 .22rem 0 .17rem;
}
.lunb-list .time{
width: 1.3rem;
margin-right: .2rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.lunb-list .money{
color: #d84545;
width: 2.5rem;
}

//轮播
var startRollOne=setInterval(lunbo,2000);
function lunbo(){
$(".lunb-list ul").animate({marginTop:"-.9rem"},800,"linear",function(){
$(this).children("li").first().remove().clone(true).appendTo(".lunb-list ul");
$(this).css("margin-top","0rem");
});
}

 注意:滚动的最外层需要设置高度然后overflow:hidden;否则在ios下面滑动页面的时候会抽搐!!!

 

 

3.关于头部导航栏返回上一级问题,使用history.back()页面不刷新问题,使用document.referrer是获取上一页的url来解决

使用href="javascript:history.back()" 那么页面不会刷新,js、ajax不会重新请求,但是有时候返回上一级页面的时候,需要刷新页面重新获取数据那么就要使用self.location=document.referrer;来返回上一级页面并刷新!!!

方法一,不刷新页面

history.back(-1):直接返回当前页的上一页,数据全部消息,是个新页面

history.go(-1):也是返回当前页的上一页,不过表单里的数据全部还在

    <header class="header flexbox flexbox-middle person-header">
        <a href="javascript:history.back()" id="hrefLogin" class="icon icon-comeback block" title="返回"></a>
        <h1 class="flexchild ellipsis">详情</h1>
    </header>

方法二,返回上一页面并刷新

<a href="javascript:" onclick="self.location=document.referrer;">返回上一页并刷新</a>

4.点击图片的时候,禁止图片显示<img onClick='return false'>

4、实现向上滚动跟向下滚动展示不同的显示效果

思路:通过对比每次滚动前后的scrollTop距离之差

        $(document).ready(function(){
            var scrollp=0,scrollt=10;
    
            $(".content").on('scroll',function(){
                scrollp = $(this).scrollTop();
                if(scrollt<=scrollp){
                    console.log('下滚');
                    $('.activate_show img').addClass('imgchange');
                    setTimeout("$('.activate_show img').removeClass('imgchange')",2000);
                }else{
                    console.log('上滚');
                    $('.activate_show img').addClass('imgchange');
                    setTimeout("$('.activate_show img').removeClass('imgchange')",2000);
                }
//                setTimeout(function(){scrollt = scrollp;},0);
                scrollt = scrollp;
            });
        }); 


通过坐标判断距离

var startX,startY,endX,endY,X,Y;
$('.content').on('touchstart',function(e){
var touch=e.originalEvent.targetTouches[0];
startX=touch.pageX;
startY=touch.pageY;
}).on('touchend',function(e){
var touch = e.originalEvent.changedTouches[0];
endX=touch.pageX;
endY=touch.pageY;
X=endX-startX;
Y=endY-startY;
console.log(Y)
if(Y>50){
$('.activate_show img').addClass('slideInRight').removeClass('slideInRight1')
setTimeout("$('.activate_show img').addClass('slideInRight1').removeClass('slideInRight')",1500);
}else if (Y<-50) {
$('.activate_show img').addClass('slideInRight').removeClass('slideInRight1')
setTimeout("$('.activate_show img').addClass('slideInRight1').removeClass('slideInRight')",1500);
}else {
$('.activate_show img').removeClass('slideInRight').removeClass('slideInRight1')
}
})

 

5、实现每次页面进来都弹出领红包弹窗 

方法:使用sessionStorage

默认div是展示,点击关闭按钮的时候,设置sessionStorage.setItem("popPacket", 1);如果页面存在这个属性,那么就关闭这个弹窗!

if (sessionStorage.getItem("popPacket")){
    $(".red-packet-dialog").hide();
}else {
    $(".red-packet-dialog").show();
    $(".is_no").hide();
}

 6、倒计时功能实现

在移动端中要保持时间格式是2018/1/31 18:31:00,不然ios下不识别会报错,当纯前端处理时

//获取开始时间
// var date = new Date();
//// var now = date.getTime();
// var nowDate = new Date(nowTime);
// var now = nowDate.getTime();
// //设置截止时间
// var endDate = new Date(endTime);
// var end = endDate.getTime();
// //时间差
// var leftTime = end-now;

    //倒计时
    var time1 = "{$rest_time}";//1天=86400秒
    var times = parseInt(time1);
    countDown(times);
    function countDown(times){
        var timer=null;
        timer=setInterval(function(){
            var day=0,
                hour=0,
                minute=0,
                second=0;//时间默认值
            if(times > 0){
                day = Math.floor(times / (60 * 60 * 24)) ;
                hour = Math.floor(times / (60 * 60)) - (day * 24);
                minute = Math.floor(times / 60) - (day * 24 * 60 ) - (hour * 60);
                second = Math.floor(times) - (day * 60 * 60 * 24) - (hour * 60 * 60) - (minute * 60);
            }
            if (day <= 9) {day = '0' + day;}
            if (hour <= 9) {hour = '0' + hour;}
            if (minute <= 9){ minute = '0' + minute;}
            if (second <= 9) {second = '0' + second;}
            //
//        console.log(hour+"小时:"+minute+"分钟:"+second+"秒");
            $(".day").html(day);
            $(".hour").html(hour);
            $(".min").html(minute)
            $(".sec").html(second)
            times--;
            if(times<=-1){
                clearInterval(timer);
            }
        },1000);
    }

7、简单日历制作

html:

    <!--日历制作-->
    <div id="calendar">
       <h4>2013年10月</h4>
       <a href="##" rel="external nofollow" rel="external nofollow" class="a1">上月</a>
       <a href="##" rel="external nofollow" rel="external nofollow" class="a2">下月</a>
       <ul class="week">
            <li>日</li>
            <li>一</li>
            <li>二</li>
            <li>三</li>
            <li>四</li>
            <li>五</li>
            <li>六</li>     
       </ul>
       <ul class="dateList"></ul>
    </div>

css:

   * {margin: 0;padding: 0}
   #calendar {width: 210px;margin: 100px auto;overflow: hidden;border: 1px solid #000;padding: 20px;position: relative}
   #calendar h4 {text-align: center;margin-bottom: 10px}
   #calendar .a1 {position: absolute;top: 20px;left: 20px;}
   #calendar .a2 {position: absolute;top: 20px;right: 20px;}
   #calendar .week {height: 30px;line-height: 20px;border-bottom: 1px solid #000;margin-bottom: 10px}
   #calendar .week li {float: left;width: 30px;height: 30px;text-align: center;list-style: none;}
   #calendar .dateList {overflow: hidden;clear: both}
   #calendar .dateList li {float: left;width: 30px;height: 30px;text-align: center;line-height: 30px;list-style: none;}
   #calendar .dateList .ccc {color: #ccc;}
   #calendar .dateList .red {background: #F90;color: #fff;}
   #calendar .dateList .sun {color: #f00;}

js:

$(function() {
 
    //必要的数据
    //今天的年 月 日 ;本月的总天数;本月第一天是周几???
    var iNow=0;
     
    function run(n) {
     
         var oDate = new Date(); //定义时间
         oDate.setMonth(oDate.getMonth()+n);//设置月份
         var year = oDate.getFullYear(); //
         var month = oDate.getMonth(); //
         var today = oDate.getDate(); ////计算本月有多少天
         var allDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
     
         //判断闰年
         if(month == 1) {
          if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
           allDay = 29;
          }
         }
     
         //判断本月第一天是星期几
         oDate.setDate(1); //时间调整到本月第一天
         var week = oDate.getDay(); //读取本月第一天是星期几
     
         //console.log(week);
         $(".dateList").empty();//每个月对应的不同,要每次清空
         
         //插入空白     
         for(var i = 0; i < week; i++) {
          $(".dateList").append("<li></li>");
         }
     
         //日期插入到dateList
         for(var i = 1; i <= allDay; i++) {
          $(".dateList").append("<li>" + i + "</li>")
         }
         //标记颜色=====================
         $(".dateList li").each(function(i, elm){
              //console.log(index,elm);
              var val = $(this).text();
              //console.log(val);
              if (n==0) {
                   if(val<today){
                   $(this).addClass('ccc')
                  }else if(val==today){
                   $(this).addClass('red')
                  }else if(i%7==0 || i%7==6 ){
                   $(this).addClass('sun')
                  }
              }else if(n<0){
               $(this).addClass('ccc')
              }else if(i%7==0 || i%7==6 ){
               $(this).addClass('sun')
              }
         });
     
         //定义标题日期
         $("#calendar h4").text(year + "" + (month + 1) + "");
        };
        run(0);
         
        $(".a1").click(function(){
         iNow--;
         run(iNow);
        });
         
        $(".a2").click(function(){
         iNow++;
         run(iNow);
        })
   });

 

 8、强制保留两位小数如:8,会在2后面补上00.即8.00   

function toDecimal2(x) {   
      var f = parseFloat(x);   
      if (isNaN(f)) {   
        return false;   
      }   
      var f = Math.round(x*100)/100;   
      var s = f.toString();   
      var rs = s.indexOf('.');   
      if (rs < 0) {   
        rs = s.length;   
        s += '.';   
      }   
      while (s.length <= rs + 2) {   
        s += '0';   
      }   
      return s;   
}

 九、对应动态添加的元素绑定事件时,需要进行事件委托

例如downctn元素是通过ajax获取渲染来的,那么这个时候,就需要委托不是通过ajax渲染出来的父级元素,进行事件委托,执行点击事件!!!

$(".security").on("click", ".downctn", function() {})

 

十、滚动模拟上拉加载

 //上滑加载
 $(window).scroll(function() {
     var winH = $(window).height();
     var scrH = $(window).scrollTop();
     var htmH = $(document).height()- $("header").height();
     if(winH + scrH >= htmH) {
        page++;
        getProduct();
     }
})

 

posted @ 2017-12-14 20:06  心向阳  阅读(948)  评论(0编辑  收藏  举报