3 回答
![?](http://img1.sycdn.imooc.com/545861b80001d27c02200220-100-100.jpg)
TA贡献1851条经验 获得超3个赞
你写的代码有很多错误
{$ (this).parent().parent().parent ()}是一个大错误,因为它以最小的变化停止
您需要将一个类添加到父 div并使用它。
jQuery(document).ready(function($) {
$(".img-upload").change(function () {
var that = $(this)
var files = $(this)[0].files
if (files != null && files[0] != null) {
var reader = new FileReader();
reader.onload = function (e) {
that.closest('.parent').find('div.img-see-upload').css({
'background-image' : 'url(' + e.target.result + ')'
});
};
reader.readAsDataURL(files[0]);
}
});
});
.img-see-upload {
height: 600px;
width: 600px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="m-3 position-relative parent">
<div class="position-absolute m-auto h-100 w-100 center-center" style="left: 0;right: 0;">
<div class="tutorial-area center-center bg-white border-0 pointer">
<button>
<img src="public/assets/img/upload.png" class="loading-logo">
</button>
<input type="file" name="image" class="pointer img-upload"/>
</div>
</div>
<div class="img-see-upload background-image-kochstream background-cover" style="background-image: url(public/assets/img/kochen.jpg)"></div>
</div>
![?](http://img1.sycdn.imooc.com/5333a01a0001ee5302000200-100-100.jpg)
TA贡献1829条经验 获得超4个赞
jQuery(document).ready(function($) {
$(".img-upload").change(function () {
console.log($(this));
var input = $(this)[0];
if (input.files) {
var reader = new FileReader(),
imgSeeUploadDiv = $(input).closest('.m-3').find('.img-see-upload')[0];
reader.onload = function (e) {
console.log($(this));
$(imgSeeUploadDiv).css({
'background-image' : `url(${e.target.result} )`,
"width": "50px",
"height": "50px"
}
);
};
reader.readAsDataURL(input.files[0]);
}
});
});
需要注意的几点:
不需要
!= null
'this' 在 'reader.onload' 函数中发生变化。
必须在元素 css 中添加 'height' 和 'width'。
您可以使用“最接近”功能来查找特定的父项
![?](http://img1.sycdn.imooc.com/533e4d470001a00a02000200-100-100.jpg)
TA贡献1842条经验 获得超21个赞
对事件侦听器使用箭头函数,如下所示:
reader.onload = (e) => {
$(this).parent().parent().parent().find('div.img-see-upload').css({
'background-image' : 'url(' + e.target.result + ')'
});
};
或者只是保存实例:
var reader = new FileReader();
var self = this;
reader.onload = function (e) {
$(self).parent().parent().parent().find('div.img-see-upload').css({
'background-image' : 'url(' + e.target.result + ')'
});
};
reader.readAsDataURL($(this).files[0]);
添加回答
举报