着手开始努力学习前端,最近遇到了个问题,网页中如果图片过长,显示一个展开的按钮遮住部分,点击展开的时候图片全部展开,点击收起的时候收起部分图片。最开始想的是用纯css3处理,但是发现css3处理的时候都是两个图片这样做的,单个并不适合。后来也是在网上看到一位朋友写的博客,图片过长的时候切图片只显示部分来了灵感。将代码以及自己解决的办法贴出来。
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>untitled</title>
<style type="text/css" media="screen">
div.crop {
height: 300px;
width: 530px;
overflow: hidden;
}
div.crop img {
margin: -2px -200px 0 0;
}
</style>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
var flag = true;//定义全局变量用来显示向上的图片还是向下的图片
$(function(){
$(".show_hide").click(function(){
console.log(flag);
if(flag){
$(this).find("img").attr("src","img/up.png");
$(this).prev(".crop").css("height","1000px");
flag = false;
}else{
$(this).find("img").attr("src","img/down.png");
$(this).prev(".crop").css("height","300px");
flag = true;
}
})
})
</script>
</head>
<body>
<div class="crop">
<img src="img/001.jpg" class="crop" alt="Paper Sculpture Large">
</div>
<div class="show_hide">
<img src="img/down.png"/>
</div>
</body>
</html>
主要就是设置div的高度比图片小,图片超出的部分用overflow:hidden属性隐藏起来,定义一个变量flag来判断当前状态是要展开还是要收起,我定义的当flag为true的时候是要展开图片,false的时候是要收起图片。展开的时候把 div的高度变成和图片高度一样,点收起的时候div高度恢复到最开始的状态。