JavaScript 长图分隔显示
JavaScript 长图分隔显示

<!DOCTYPE html>
<html>
<meta charset="utf8">
<head>
<style>
* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}
.img-container {
	width: 50%;
	height: 96vh;
	display:inline-block;
	position: relative;
	overflow: hidden;
	border: 1px solid black;
}
.img-container > img {
	position: absolute;
}
/*! nth-child 表示第几个子元素,nth-of-type 表示第几个该类型的子元素 */
.img-container:nth-of-type(2) > img {
	transform: translateY(-50%);
}
.img-type-fill {
	width: 100%;
	height: 100%;
}
#img1, .img-type-2column {
	width: 100%;
	height: 200%;
}
#input {
	display: none;
}
#selectBtn {
	width: 100%;
	height: 3.5vh;
	overflow: hidden;
	border: 1px solid black;
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>
<script>
window.()=>{
const imgContainer = document.getElementsByClassName("img-container");
const img1 = document.getElementById("img1");
const img2 = document.getElementById("img2");
const input = document.getElementById("input");
const selectBtn = document.getElementById("selectBtn");
//由于原生的input控件实在太丑了,于是就将其隐藏,通过点击按钮间接触发该控件
selectBtn.addEventListener("click", ()=>{
	input.click();
});
img0.()=>{
	if(img0.width<img0.height) {
		imgContainer[0].style.width="49%";
		imgContainer[1].style.display="inline-block";
		img0.className = "img-type-2column";
		img1.src = img0.src;
	} else {
		imgContainer[0].style.width="100%";
		imgContainer[1].style.display="none";
		img0.className = "img-type-fill";
	}
}
input.addEventListener("change", function(){
	const file = this.files[0];
	console.log(file)
	//如果在input[type=file]中设置了accept="image/*",可以省略如下判断
	//另外,百度上下载的jfif 被认为是 timg.jfif,而不是image格式
	if(!/image\/\w+/.test(file.type)){ 
		alert("文件必须为图片!"); 
		return false; 
	}
	const reader = new FileReader();
	reader.readAsDataURL(file); 
	reader.onload = function(e) {
		img0.className = "";
		img0.style = "";
		img0.src = e.target.result;
	}
});
}
</script>
</head>
<body>
<!-- 特别要注意,这里必须合并成一行,因为空格或者换行都变成中间的空隙 -->
<span class="img-container"><img id="img0"/></span><span class="img-container"><img id="img1"/></span>
<div id="selectBtn">请选择图片</div><input id="input" type="file" accept="image/*, timg/jfif">
</body>
</html>

相关文章:

  • 2022-12-23
  • 2021-06-01
  • 2021-12-22
  • 2022-12-23
  • 2021-12-09
  • 2022-12-23
  • 2021-05-31
  • 2021-07-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案