我有一个文件输入(图片),我想根据更大的内容设置div
的{{1}}:class
或width
。< / p>
我的代码不起作用(只有最后height
语句),if
的类永远不会更改,无论上传的图像如何。
这是我的HTML:
div
这是我的JavaScript:
<div class="row">
<div class="col-md-12">
<div id="blah" class="profilePic">
<img src="profilkep.jpg" />
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<input type="file" onchange="previewFile()">
</div>
</div>
答案 0 :(得分:0)
您的代码似乎很好。这是一个工作片段
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
if (file.width < file.height) {
document.getElementById("blah").setAttribute("class", "blahblah");
} else {
document.getElementById("blah").setAttribute("class", "profilePic");
}
}
&#13;
.blahblah {
border: 1px solid red;
}
.profilePic {
border: 1px solid blue;
}
&#13;
<div class="row">
<div class="col-md-12">
<div id="blah" class="profilePic">
<img src="http://i.imgur.com/MxPGcXu.gif" />
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12" id="blah">
<input type="file" onchange="previewFile()">
</div>
</div>
&#13;
答案 1 :(得分:-1)
问题是您有两个相同的ID blah
。所有ID都必须是唯一的。
file.width
和file.height
始终未定义。这是修复:
<div class="row">
<div class="col-md-12">
<div id="blah">
<img id="profileImage" src="profilkep.jpg" />
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<input type="file" onchange="previewFile()">
</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
var imageWidth = $('#profileImage').width();
var imageHeight = $('#profileImage').height();
if (imageWidth < imageHeight) {
console.log('width < height');
document.getElementById("blah").setAttribute("class", "blahblah");
} else {
console.log('width > height');
document.getElementById("blah").setAttribute("class", "profilePic");
}
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
</script>