概述
前言
实际项目中,关于页面的方面经常会碰到几个让人头疼的问题。举个栗子:图片自适应问题;底部footer究竟该怎样定位才能保证不管主体部分内容多少,都要能够放在最下面的理想位置。
图片大小自适应
一般而言,网站为了布局优美,放置图片的方框都是固定大小的容器(防止数据库中的图片大小和容器大小相差太大,影响布局)。
根据图片大小和容器大小的比较,分为4类:
1、前两类 图片高度 < 容器高度 && 图片宽度 < 容器宽度 || 图片高度 > 容器高度 && 图片宽度 > 容器宽度
解决方案:设置图片宽高都是父容器的100%。
2、图片高度 < 容器高度 && 图片宽度 > 容器宽度
解决方案:设置图片高度都是父容器的100%,宽度自适应(auto)。
3、图片高度 > 容器高度 && 图片宽度 < 容器宽度
解决方案:设置图片宽度都是父容器的100%,高度自适应(auto)。
具体实施可以参照下面:
<script >
function initImg(rollimg){
var pHeight = $(rollimg).parent().height();
var pWidth = $(rollimg).parent().width();
console.log(pHeight + ',' + pWidth );
$(rollimg).css("width","100%");
// $(rollimg).css("height","100%");
var imgHeight = $(rollimg).height();
var imgWidth = $(rollimg).width();
console.log("imgHeight:"+imgHeight);
if(imgHeight < pHeight){
$(rollimg).removeAttr("style").css({"height":"100%"});
}
if(imgHeight < pHeight && imgWidth > pWidth){
$(rollimg).removeAttr("style").css({"height":"100%"}).css("width","auto");
}
}
//图片自适应
window.onload=function(){
$.each($(".rollimg"),function(i,rollimg){
if(rollimg.complete){
console.log("从缓存中获取");
initImg(rollimg);
}else{
$(this).load(function(){
console.log("从服务器中获取");
initImg(rollimg);
});
}
});
};
</script>
关于footer的定位
使用 position:absolute/fixed/relative; 或者让主体部分的内容自动把footer撑起到下面都不能保证在各种环境下显示正常,都存在问题。
position:absolute;一旦主体内容特别多,大于clientHeihgt,底部footer就会遮住主体内容。
position:fixed/relative;或者让主体部分的内容自动把footer撑起到下面。一旦主体内容特别少,小于clientHeihgt,底部footer就会跑到这面来很难看。
解决方案:几种定位方式灵活使用,配合jq判断页面内容高度和浏览器高度的比较。
具体实施可以参照下面:
<script>
$(function () {
function initFooter(){
var height = $("header").height() + $(".main-bgImg").height() + $("footer").outerHeight();
//console.log($("header").height()+","+$(".all-info-con").height()+","+$("footer").outerHeight());
//console.log("窗口高度:"+$(window).height()+","+"总高度:"+height);
heightRsize();
$(window).resize(function(){
heightRsize();
});
//内容过少时footer自动到底部
function heightRsize(){
if($(window).height() > height){
$("footer").css({"position":"absolute","width":"100%","bottom":"0"})
}else{
$("footer").removeAttr("style");
}
}
}
initFooter();
})
</script>
总结
这两个问题几乎每个项目都会遇到,而解决方法因人而异,大概拥有几年前端经验的人也会对这两个问题比较烦心吧。如果您有更好的方法,欢迎留言交流!
最后
以上就是舒适方盒为你收集整理的图片自适应和footer的定位方式的全部内容,希望文章能够帮你解决图片自适应和footer的定位方式所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复