动态生成Swiper效果

来源:互联网 发布:淘宝脱胶险怎么设置 编辑:程序博客网 时间:2024/06/05 16:40

一、 初始化 swiper-container ,不能直接 display:none;

<style>

 .swiper-bookSheet{height:0px;}/*swiper初始化高度为0,不能display:none;*/

 </style>

二、HTML标签生成

  <div class="swiper-container swiper-bookSheet"style="top:0px;background:rgba(102,102,102,0.5);">  </div>
  <div class="ele"></div>

三、触发Swiper 动态生成的 js


 <script>
  var swiperContainer = '<div class="swiper-wrapper"></div><div class="swiper-pagination"  style="height: 50px; z-index: 200; "></div>';
  $(".ele").click(function(){ //点击之后动态生成 swiper
   $(".swiper-bookSheet").append(swiperContainer);
 $(".swiper-bookSheet").css("height", "100%");
 for (var i = 0; i < spanLength.length; i++) {
        var imgSrc = $(spanLength[i]).children(".big").attr("src");
        /*列表img */
        var child = '<div class="swiper-slide" style="display:table;height: 100%;width:100%;"><p style="text-align: center;vertical-align: middle;position: relative; display:table-cell;overflow: hidden;height:100%;width:100%;"><span class="top:50%;" ><img onload="javascript:DrawImage(this)" style="z-index: 200;top:-50%;left:-50%;max-width:100%;max-height:100%;" class="getbookimg" src="' + imgSrc + '" /></span></p></div>';
        var btn = '<span class="swiper-pagination-bullet"></span>';
        $(".swiper-wrapper").append(child);
        $(".swiper-pagination").append(btn);
}
var swiper = new Swiper('.swiper-container',{
        pagination: '.swiper-pagination',
        paginationClickable: true,
        nextButton: '.swiper-button-next',
        prevButton: '.swiper-button-prev',
        speed: 600,
        initialSlide: 0,
        observer: true,
        observeParents: true,
    });
 swiper.slideTo(slidNum, 0, false);//跳转到当前点击的图片
  
  });
/* img onload 之后获取动态生成图片的高度 */

/* 只有 onload 之后才能获取到图片的高度,然后实现动态生成的图片垂直居中 , */

var flag = false;
function DrawImage(ImgD) {
    var image = new Image();
    var iwidth = 80;
    var iheight = 80;
    if (ImgD.width > 0 && ImgD.height > 0) {
        flag = true;
        if (ImgD.width / ImgD.height >= iwidth / iheight) {
            if (ImgD.width > iwidth) {
                /*ImgD.width=iwidth; ImgD.height=(ImgD.height*iwidth)/ImgD.width; */
                ImgD.width = ImgD.width;
                ImgD.height = ImgD.height;
            } else {
                ImgD.width = ImgD.width;
                ImgD.height = ImgD.height;
            }
        } else {
            if (ImgD.height > iheight) {
                /*ImgD.height=iheight; ImgD.width=(ImgD.width*iheight)/ImgD.height; */
                ImgD.width = ImgD.width;
                ImgD.height = ImgD.height;
            } else {
                ImgD.width = ImgD.width;
                ImgD.height = ImgD.height;
            }
        }
    }
}
/*调用:<img src="图片" onload="javascript:DrawImage(this)">  */

  </script>



0 0
原创粉丝点击