swiper支持动态加载数据

本文介绍如何使用Swiper插件实现图片轮播效果,并动态加载数据。通过在HTML中设置Swiper容器,结合JavaScript动态填充图片,最后完成Swiper的初始化,解决了动态加载数据的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用swiper插件动态加载数据:动态获取完数据之后,在初始化swiper.


1、在<head>标签里面加入swiper的css和js文件

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/css/swiper.min.css">

 <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.min.js"></script>

2、html如下:

    <div class="swiper-container"><!--swiper容器[可以随意更改该容器的样式-->  
        <div class="swiper-wrapper" id="swiperWrapper">  
          
            
        </div>    
        <div class="swiper-button-prev swiper-button-white"></div><!--前进按钮-->  
        <div class="swiper-button-next swiper-button-white"></div><!--后退按钮-->  
    </div> 

3、js如下:

   function handlePascreenImg(datas){
		var len = datas.length,
			DOMObj = null,        //img
			obj = null,           //保存当前对象
			img_path = '',        //图片名
			price = '',           //霸屏每秒的价钱
			paScreenType = '',    //霸屏的type
			name = '',            //霸屏图片的名字
			src = '';             //图片路径

		// 清除上次的数据
		$('#swiperWrapper').empty();
		for( var i=0;i<len;i++ ){
			obj = datas[i],
			img_path = obj.img_path,
			price = obj.price,
			paScreenType = obj.type,
			name = obj.name,
			src = globalConfig.pre_api_url + '/wxwall_api/good/img/' + img_path;

			var imgList =  '<div class="swiper-slide">' +
						   '<img id="img'+i+'"  src="'+src+'"    name="'+name+'"  paScreenType="'+paScreenType+'"  price="'+price+'" >' +
						   '</div>';

			$('#swiperWrapper').append(imgList);
			if( i == len-1 ){
				$('#paScreenTxt').text($('#img0').attr('name'));

				// 在获取数据之后,在对swiper进行初始化,解决动态加载的问题
		    	       mySwiper = new Swiper(".swiper-container",{  
	            	                direction:"horizontal",/*横向滑动*/  
	            	                // loop:true,/*形成环路(即:可以从最后一张图跳转到第一张图*/    
	            	               prevButton:".swiper-button-prev",/*前进按钮*/  
	            	               nextButton:".swiper-button-next",/*后退按钮*/
	            	               onSlideChangeStart:function(swiper){
	            		              // 监听swiper滑动事件,更换图片上方文字
	            		             var index = swiper.activeIndex;
	    		                     $('#paScreenTxt').text( $('#img'+index).attr('name') );
	            	               }  
        		      });
			}
		}

	}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值