3 回答

TA貢獻1851條經(jīng)驗 獲得超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>

TA貢獻1829條經(jīng)驗 獲得超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' 函數(shù)中發(fā)生變化。
必須在元素 css 中添加 'height' 和 'width'。
您可以使用“最接近”功能來查找特定的父項

TA貢獻1842條經(jīng)驗 獲得超22個贊
對事件偵聽器使用箭頭函數(shù),如下所示:
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]);
添加回答
舉報