我正在一个django项目上工作,需要添加一个个人资料图片,这是有效的;但问题是,当有人上传一张相当长或相当宽的照片时,个人资料图像显示看起来会很奇怪。我尝试通过将其添加到base.html
<link rel="stylesheet" href="{% static 'cropperjs/dist/cropper.min.css' %}">
<script type="module" src="{% static 'cropperjs/dist/cropper.min.js' %}">
我只是想遵循文档我保留了我的edit-profile.html
{% block content %}
<div class="image-box">
<img src="{{ request.user.userprofile.profile_image.url }}" id="image" width="300px">
</div>
{% endblock %}
和我的edit-profile.js
console.log('Hello there')
var $image = $('#image');
$image.cropper({
aspectRatio: 16 / 9,
crop: function(event) {
console.log(event.detail.x);
console.log(event.detail.y);
console.log(event.detail.width);
console.log(event.detail.height);
console.log(event.detail.rotate);
console.log(event.detail.scaleX);
console.log(event.detail.scaleY);
}
});
var cropper = $image.data('cropper');
但是当我runserver
和我检查页面时,我看到错误
edit_profile.js:3 Uncaught ReferenceError: $ is not defined
at edit_profile.js:3:14
所以我尝试创建一个正常的HTML文件,并与javascript文件链接,然后尝试初始化cropper。index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="forum/static/cropperjs/dist/cropper.css">
<meta http-equiv="Access-Control-Allow-Origin" content="*"/>
<title>Test site</title>
</head>
<body>
<div class="image-box">
<img src="yor.png" id="image" width="300px">
</div>
<script type="text/javascript" src="main.js"></script>
<script type="module" src="cropperjs/dist/cropper.js" crossorigin="anonymous"></script>
</body>
</html>
和main.js
// import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
const image = document.getElementById('image');
const cropper = new Cropper(image, {
aspectRatio: 16 / 9,
crop(event) {
console.log(event.detail.x);
console.log(event.detail.y);
console.log(event.detail.width);
console.log(event.detail.height);
console.log(event.detail.rotate);
console.log(event.detail.scaleX);
console.log(event.detail.scaleY);
},
});
我得到了这组错误
Access to script at 'file:///C:/Users/McDonald/Documents/Projects/cropperjs/dist/cropper.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, chrome-untrusted, https.
index.html:17 GET file:///C:/Users/McDonald/Documents/Projects/cropperjs/dist/cropper.js net::ERR_FAILED
main.js:2 Uncaught SyntaxError: Cannot use import statement outside a module (at main.js:2:1)
越来越混乱了,我不知道我做错了什么
$
是jQuery常用的快捷方式。您在第3行使用它来选择id为"image"的元素。
var $image = $('#image');
你的(第一个)错误是说$
没有定义,这意味着你没有加载jQuery。确保通过在HTML中的某个地方使用脚本标记包含jQuery来加载它。比如:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
那么你应该能够毫无问题地运行你的第一个代码!