django模板中使用JQ代码实现瀑布流显示效果
Posted angelyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django模板中使用JQ代码实现瀑布流显示效果相关的知识,希望对你有一定的参考价值。
settings中的配置不再详细说明
一.路由代码
from django.contrib import admin from django.conf.urls import url from app import views urlpatterns=[ url(r‘^admin‘,admin.site.urls), # 页面显示get请求 url(r‘^imgs.html$‘,views.imgs), # 获取图片的ajax请求 url(r‘^get_imgs.html$‘,views.get_imgs), ]
二.视图函数
from app import models from django.http import JsonResponse from django.shortcuts import render def imgs(request): return render(request, ‘img.html‘) def get_imgs(request): nid = request.GET.get(‘nid‘) # id__gt=nid表示查询id大于多少的数据,nid由模板的ajax传过来 img_list = models.Img.objects.filter(id__gt=nid).values(‘id‘, ‘src‘, ‘title‘) # queryset对象转列表 img_list = list(img_list) ret = { ‘status‘: True, ‘data‘: img_list } return JsonResponse(ret)
三.models代码
from django.db import models # Create your models here. class Img(models.Model): src = models.FileField(max_length=32, verbose_name=‘图片路径‘, upload_to=‘static/upload‘) title = models.CharField(max_length=16, verbose_name=‘标题‘) summary = models.CharField(max_length=128, verbose_name=‘简介‘) class Meta: verbose_name_plural = ‘图片‘ def __str__(self): return self.title
四.模板代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .w { width: 1000px; margin: 0 auto; } .item { width: 25%; float: left; } .item img { width: 100%; } </style> </head> <body> <div>图片</div> <div class="w" id="container"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <script src="/static/JS/jquery-3.3.1.min.js"></script> <script> $(function () { var obj = new ScrollImg(); obj.fetchImg(); obj.scrollEvent(); }); function ScrollImg() { this.NID = 0; this.LASTPOSITION = 3; this.fetchImg = function () { var that = this; $.ajax({ url: ‘/get_imgs.html‘, type: ‘GET‘, //前端传到后台的获取数据量 data: {nid: that.NID}, dataType: ‘JSON‘, success: function (arg) { var img_list = arg.data; //循环列表获取index:索引,v:图片信息(id,src,title) $.each(img_list, function (index, v) { //取4的余数,始终返回的是0,1,2,3的索引 var eqv = (index + that.LASTPOSITION + 1) % 4; console.log(eqv); //创建img标签 var tag = document.createElement(‘img‘); //img标签的src地址等于图片的src地址 tag.src = ‘/‘ + v.src; $(‘#container‘).children().eq(eqv).append(tag); //如果index是最后一个, if (index + 1 == img_list.length) { //测试使用,始终只取开始那几条数据 that.LASTPOSITION = eqv; //取完该页面显示的条数后,再去后面的条数 //that.NID = v.id; } }) } }) }; this.scrollEvent = function () { var that = this; //绑定滚轮事件 $(window).scroll(function () { //滚动条可滑动的高度 var scrollTop = $(window).scrollTop(); //窗口高度 var winHeight = $(window).height(); //文档高度 var docHeight = $(document).height(); //如果滑到最后,执行获取图片 if (scrollTop + winHeight == docHeight) { that.fetchImg(); } }) } } </script> </body> </html>
以上是关于django模板中使用JQ代码实现瀑布流显示效果的主要内容,如果未能解决你的问题,请参考以下文章