上传图片
- 美化上传按钮:利用绝对布局
补充知识:
<style>
label.change-style{
position: relative;
display: inline-block;
text-align: center;
line-height: 30px;
}
#upload-file2{
width:50px;
position: absolute;
top: 0;
left: 0;
opacity:0;
}
ul{
list-style-type: none;
}
li{
margin:15px 0 ;
}
//隐去没有图片时的空白块
img[src=""]{
opacity: 0;
}
.change-style img{
width:100px;
height: auto;
vertical-align: top;
}
</style>
<body>
<div>
<h2>上传照片[type="file"]并预览</h2>
<ul>
<li>
<label for="upload-file">上传文件</label>
<input type="file" accept="image/*" id="upload-file">
</li>
<li>
<label class="change-style">上传文件
<img src="">
<input id="upload-file2" type="file" accept="image/png,image/jpeg,image/gif,image/jpg">
</label>
</li>
</ul>
</div>
<div>
<h2>单选[type="radio"]</h2>
<ul>
<li>
<label for="upload-file">上传文件</label>
<input type="file" accept="image/*" id="upload-file">
</li>
<li>
<label class="change-style">上传文件
<img src="">
<input id="upload-file2" type="file" accept="image/png,image/jpeg,image/gif,image/jpg">
</label>
</li>
</ul>
</div>
// 使用FileReader对象读文件
$(document).on('change','#upload-file2', function(){
const fileUpload = $('#upload-file2').get(0);
const picture = fileUpload.files[0];
console.log(picture)
if(window.FileReader){
// 当前浏览器是否支持FileReader
var reader = new FileReader();
reader.onload = function(e){
const pictureUrl = e.target.result;
$('.change-style img').attr('src',pictureUrl);
}
reader.readAsDataURL(picture)
}
})
单选多选
<ul>
<li>
<h2>单选[type="radio"]</h2>
<label>你喜欢周杰伦吗
<input name="radio" type="radio" checked value="1">喜欢
<input name="radio" type="radio" class="like-check" value="2">喜欢的
</label>
</li>
<li>
<label>你多大了? <input class="age" type="text" oninput="value=value.replace(/[^\d]/g,'')" checked ></label>
</li>
<li>
<h2>复选框[type="checkbox"]</h2>
<label><input type="checkbox" class="all-check">全选</label>
<label><input type="checkbox" name="all-check" value="1">1</label>
<label><input type="checkbox" name="all-check">2</label>
<label><input type="checkbox" name="all-check">3</label>
<button>提交</button>
</li>
</ul>
<script>
//判断是否选中
if($('.like-check')[0].checked){
console.log($('.like-check').text())
}
// 判断是否全选
const length = $('input[name="all-check"]').length;
//点击全选按钮
$('.all-check').on('change', function() {
if($('.all-check')[0].checked){
$('input[name="all-check"]').prop('checked',true);
}else{
$('input[name="all-check"]').prop('checked',false);
}
})
// 点击下面复选框
$('input[name="all-check"]').on('change', function() {
let checkedLength = $('input[name="all-check"]:checked').length;
if(length===checkedLength){
// 用attr的话只在第一次点击的时候有用
$('.all-check').prop('checked',true);
}else{
$('.all-check').prop('checked',false);
}
})
$('button').click(function(){
// 获取全选内容
let checkedContent = [];
$('input[name="all-check"]:checked').each(function(index,item){
checkedContent.push($(this).parent().text());
})
})
</script>