jq添加<img>点击事件调用上传图片方法并回显图片
作者:程序员11 时间:2023-05-16 人气:279 QQ交流群\邮箱:1003265987@qq.com
jq添加<img>点击事件调用上传图片方法并回显图片
要展示的内容
1.html添加如下元素
<img src="https://img1.baidu.com/it/u=1983462487,1113805563&fm=26&fmt=auto" alt="" width="80" id="logoImg" onclick="imgChange()"> <input type="file" style="width: 305px;display: none" name="logoPicUrl" multiple="multiple" id="logoPicUrl" autocomplete="off" accept="image/x-png,image/gif,image/jpeg,image/bmp">
2.js添加如下方法
/**
* 点击图片事件
*/
function imgChange() {
$('#logoPicUrl').click();
$("#logoPicUrl").unbind().change(function(e) {
if ($('#logoPicUrl').val() == '') {
return;
}
changeImg(e,$(this).val());
});
}
/**
* 改变图片
*/
function changeImg(e,filePath) {
fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
//检查后缀名
if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
showError('文件格式必须为:png/jpg/jpeg');
return;
}
//获取并记录图片的base64编码
var reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onloadend = function() {
// 图片的 base64 格式, 可以直接当成 img 的 src 属性值
var dataURL = reader.result;
console.log(dataURL)
// 显示图片
$("#logoImg").attr('src',dataURL);
};
}完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>点击图片上传并回显</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<style>
</style>
</head>
<body>
<img src="https://img1.baidu.com/it/u=1983462487,1113805563&fm=26&fmt=auto" alt="" width="80" id="logoImg" onclick="imgChange()">
<input type="file" style="width: 305px;display: none" name="logoPicUrl" multiple="multiple" id="logoPicUrl" autocomplete="off"
accept="image/x-png,image/gif,image/jpeg,image/bmp">
</body>
<script>
/**
* 点击图片事件
*/
function imgChange() {
$('#logoPicUrl').click();
$("#logoPicUrl").unbind().change(function(e) {
if ($('#logoPicUrl').val() == '') {
return;
}
changeImg(e,$(this).val());
});
}
/**
* 改变图片
*/
function changeImg(e,filePath) {
fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
//检查后缀名
if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
showError('文件格式必须为:png/jpg/jpeg');
return;
}
//获取并记录图片的base64编码
var reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onloadend = function() {
// 图片的 base64 格式, 可以直接当成 img 的 src 属性值
var dataURL = reader.result;
console.log(dataURL)
// 显示图片
$("#logoImg").attr('src',dataURL);
};
}
</script>
</html>链接:https://blog.csdn.net/weixin_42402326/article/details/121099136
温馨提示:
欢迎阅读本文章,觉得有用就多来支持一下,没有能帮到您,还有很多文章,希望有一天能帮到您。
jq添加<img>点击事件调用上传图片方法并回显图片---相关文章
HTML5-热门文章
活跃用户












