我正在做一个项目,我在想,我想在超文本标记语言中制作一个按钮,它将在Django views.py中控制。所以基本上,当有人点击按钮时,背景变暗并保存下来,我的意思是,如果有人刷新页面,背景仍然是暗的。我想知道是否有可能做到这一点。
谢谢。
发布于 2021-09-26 14:15:49
这是非常容易做到的。按钮点击可以连接到jquery点击函数,该函数还包括一个ajax调用:
$('#id_button).click(function(){
$('body').css({'background-color': 'dark-gray'})
$.post({% url 'change-background-color' %}, {color: 'dark-gray'}, function(){
location.reload() // to refresh the page with new background color
})
})
# urls.py
add the following path
path('change-background-color/', views.change_background_color, name='change-background-color'),
# views.py
add the following view
def change_background_color(request):
color = request.POST.get('color')
# you could save the input to a model BackgroundColor as an instance or
update a current record.
# creating an instance
BackgroundColor.objects.create(bg_color=color)
return JsonResponse({'response': 'successfully changed color'})现在剩下的就是确保您的html将背景颜色设置为引用Model实例的变量,您在Ajax调用中将颜色保存在该实例中
<body style='background-color:{{bg_color}}'></body>https://stackoverflow.com/questions/69335539
复制相似问题