使用jq 仿 swper 图片左右滚动

时间:2024-06-23 17:07:20
<div>
<div class="change-num">/</div>
<div class="box">
<div class="box-ul">
<div class="box-li">
<span></span>
<img src="http://pic71.nipic.com/file/20150610/13549908_104823135000_2.jpg">
</div>
<div class="box-li">
<span></span>
<img src="http://img.zcool.cn/community/0142135541fe180000019ae9b8cf86.jpg@1280w_1l_2o_100sh.png">
</div>
<div class="box-li">
<span></span>
<img src="http://img07.tooopen.com/images/20170316/tooopen_sy_201956178977.jpg">
</div>
<div class="box-li">
<span></span>
<img src="http://res.supervolleyball.com/1/advisoryrelease/jpg/0107c578-01c6-4205-b397-31afe7a88d87.jpg">
</div>
</div>
</div>
<div class="text-contet">
文字文字文字文字文字文字文字文字
</div>
</div> <script>
$(".text-contet").css("height", innerHeight - + 'px');
/*
* sX 记录每次点击的x轴位置
* mX 记录每次滑动结束时的x轴位置
* msX = mX - sX 每次滑动长度
* index 当前图片显示的序号
* num 图片的总数量
* lN 当前图片的偏移量
* nLN 移动成功后的图片left偏移量
*/
var changeNum = $(".change-num");
var boxs = $(".box");
var box = $(".box-ul");
var num = box.children(".box-li").length, index = ;
var sX, mX, msX, lN = , nLN = ;
boxs.on("touchstart", function (ev) {
ev = ev || event
ev.preventDefault();
sX = ev.originalEvent.changedTouches[].clientX;
}).on("touchmove", function (ev) {
ev = ev || event;
ev.preventDefault();
mX = ev.originalEvent.changedTouches[].clientX;
msX = mX - sX;
nLN = lN + msX;
        /*
        * 如果nLN大于0, 那么不可以滑动
        * 如果nLN小于(1 - num) * 360 , 那么不可以滑动
        */
if (nLN > ) nLN = ;
if (nLN < ( - num) * ) nLN = ( - num) * ;
box.css("left", nLN + 'px');
}).on("touchend", function (ev) {
ev = ev || event;
ev.preventDefault();
if (msX > ) {
          //右滑动
                nLN = lN + ;
index --;
}
else if (msX < -) {
        // 左滑动
                nLN = lN - ;
index ++;
}
else nLN = lN;
if (nLN > ) {
nLN =
index = ;
}
if (nLN < ( - num) * ) {
nLN = ( - num) * ;
index = num;
}
box.animate({ left: nLN + "px" }, );
        //图片滑动成功, 恢复默认值
            lN = nLN; mX = ; msX = ;
changeNum.text(index + "/" + num);
});
</script>
<style>
.box {
  width: 360px;
  height: 300px;
  overflow: hidden;
  background: #e5e5e5;
}
.box-ul {
  position: relative;
  height: 300px;
  left: 0;
  font-size: 0;
  white-space: nowrap;
}
.box-li {
  display: inline-block;
  vertical-align: middle;
  width: 360px;
  height: 300px;
  text-align: center;
}
.box-li > span {
  display: inline-block;
  vertical-align: middle;
  width: 0px;
  height: 300px;
}
.box-li > img {
  display: inline-block;
  vertical-align: middle;
  max-height: 300px;
  max-width: 360px;
}
.text-contet {
  -webkit-overflow-scrolling: touch;
  overflow-x: hidden;
  overflow-y: scroll;
  width: 360px;
}
</style>