日期:2014-05-16  浏览次数:20715 次

背景图片如果小于页面高度时,背景图片固定 这个样式怎么写。
背景图片高度是1400像素,网页高度是1900像素,到浏览到第三屏时背景图片固定。这个怎么写,这问题不太好描述,不知道能不能看明白。

------解决方案--------------------
用jquery scroll()来侦测是否浏览到第三屏,然后添加一个class,使得background-position, fixed.

jQuery(window).scroll(function(){
    if(jQuery(window).scrollTop() > 1399){
        jQuery('html').addClass('scrolled');
    }else{
        jQuery('html').removeClass('scrolled');
    }
});


html {
    background:url(image.jpg);
    background-repeat: no-repeat;
    background-position: top left;
}

html.scrolled {
    background-attachment:fixed;
    background-position: bottom left;
}

------解决方案--------------------
算是笨方法 你参考
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
*{padding:0; margin:0;}
body{background:url(http://b.hiphotos.baidu.com/album/w%3D2048/sign=19d4e347c2fdfc03e578e4b8e0078694/83025aafa40f4bfb2ac58bed024f78f0f7361875.jpg) 50% 0 no-repeat;}
body.over{background:url(http://b.hiphotos.baidu.com/album/w%3D2048/sign=19d4e347c2fdfc03e578e4b8e0078694/83025aafa40f4bfb2ac58bed024f78f0f7361875.jpg) 50% bottom no-repeat fixed;}
.box{height:5000px;}
</style>
</head>

<body>
<div class="box"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var winHeight=$(window).height();
var maxHeight=3355-winHeight; //3355为背景图片高度
$(window).scroll(function(){
if($(this).scrollTop()>maxHeight){
$("body").addClass("over");
}else{
$("body").removeClass("over");
}
});
});
</script>
</body>
</html>