javascript - 居中背景图片并在上方添加背景色

标签 javascript html css background background-image

我用了这个帖子Stretch and scale a CSS image in the background - with CSS only弄清楚如何拉伸(stretch)我的背景图像以适应尺寸。我正在使用背景大小:封面;

但恐怕,这不是我需要的安静。我不知道(一个很好的方法)该怎么做: 假设我有一张分辨率非常高的图像,例如 3840px x 1024px

要求:

  1. 图片居中
  2. Viewport width < 1280px:1280px 的固定宽度,可水平滚动 视口(viewport)宽度 >= 1280px:无水平滚动,显示更多背景图片
  3. 如果网站的内容真的很长(超过 1024 像素),我想在图像上方添加一种颜色,例如浅蓝色,如果图像的上半部分是天空,那么背景色似乎是图片。

当前的实现(糟透了): 图像被切成 3 个偶数 block 。中间部分是内容部分的背景。如果屏幕宽度增加,将显示中间部分左右 2 个 div,它们以图像的左右部分作为背景)。每次调整窗口大小时,都会使用 js 计算此侧 div 的大小(高度和宽度)。背景图像的偏移量在 Chrome 中有效,但在 Firefox 中左侧 div 存在问题。

代码是:

var PageWidth = 1280;
var SideImageWidth = 1280;
function calculateImageSet(){

    var bodyWidth = $('body').width();
    var fillerSize = Math.floor((bodyWidth - PageWidth)/2);

    if(bodyWidth < PageWidth){
        $('#fillerLeft').hide();
        $('#fillerRight').hide();
    }
    else{
        var imageOffset = SideImageWidth - fillerSize;
        var mainHeight = $('#main').outerHeight();
        $('#fillerLeft').width(fillerSize).height(mainHeight).show();
        # Doesn't seem to work
        if($.browser.mozilla){
            $('#fillerLeft').css('background-position', '-'+imageOffset+'px 0px');
        }
        $('#fillerRight').width(fillerSize).height(mainHeight).show();
    }
}

有什么好的方法吗?没有js?

如果您不明白任何要求,请询问。

谢谢

编辑: 我有一个(几乎可行的)方法:

#main{
    background-color: #d4eaff;
    background-image: url('forest-wide.jpg');
    background-repeat: no-repeat;
    background-size: auto 1280px;
    background-position: center top;
    min-width: 1280px;
}

如果内容不高于 1024 像素,这很好,但是当它超过 1024 像素时,它会在底部添加蓝色,所以此时我必须将背景位置更改为底部居中。

最佳答案

好吧兄弟,如果你正在尝试的是获得一个完全拉伸(stretch)的背景图像,我想这会对你有所帮助....纯基于 CSS 的作品适用于 Safari 3+、Chrome Whatever+、IE 9+、Opera 10+, 火狐 3.6+

html { 
  background: url(images/bg.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

关于javascript - 居中背景图片并在上方添加背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22009459/

相关文章:

css - 不同的背景渐变

javascript - ClassName 样式在 react 中不起作用

html - 元素上边距似乎没有改变

html - 所以聊天: how to make the sidebar not respond to scroll event?

html - 无法将视频放在 div 元素后面

jquery - 横幅 slider 脚本在 Safari、Chrome 中无法正常工作

html - CSS 两个文本列动态并排

javascript - 如何在 GitHub 上 fork 我自己的要点?

javascript - 如何使用单击表格单元格(除了单击 jQuery 中的选择框)

javascript - JavaScript 如何对 == 进行类型转换?