html - 覆盖背景使背景图像无响应

标签 html css

#section{
    position: absolute;
    top:0;
    height: 100%;
    width:100%;
    background: url("http://cdn9.howtogeek.com/wp-content/uploads/2010/05/ubuntu-human-1440x900.jpg") no-repeat center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
<body>
    <section id="section"></section>
</body>

background-size 设置为 cover 时,图像会更改其大小以在窗口大小更改时覆盖窗口。 有没有办法在开始时完全覆盖 background,然后在更改窗口大小后使图像无响应?

最佳答案

如果你想让你的背景图片在加载时填满屏幕,然后不调整大小(我会重新考虑 - 但也许我没有看到大图,没有双关语;))

一个可能的选择是在单独的 div 中加载图像,设置 z-index:-9999; (这将使 div 位于所有其他 div 的下方),然后使用 javascript 确定图像/div 覆盖整个页面时的大小,并使用 javascript 更改 div 的大小 element.style.width = ""

window.onload = function(){
  theWidth = document.getElementById("background").offsetWidth;
  theHeight = document.getElementById("background").offsetHeight;
  document.getElementById("background").style.width = theWidth;
  document.getElementById("background").style.height = theHeight;
}
#background{
    position: absolute;
    top:0;
    height: 100%;
    width:100%;
    background: url("http://cdn9.howtogeek.com/wp-content/uploads/2010/05/ubuntu-human-1440x900.jpg") no-repeat center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
<body>
    <section id="background"></section>
    <section id="your_content"></section>
</body>

如果您希望它不会溢出并在加载后提供水平滚动,请将背景包裹在 <div style = 'max-width:100%; overflow:hidden; position:relative;'> 中。 div - overflow:hidden;将隐藏所有溢出 div 边界的内容(比如包含图像的 div,它将保持原始宽度,而当前宽度可能更小)和 position:relative; overflow:hidden; 需要申请(IIRC - 如果我没记错的话)

关于html - 覆盖背景使背景图像无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32861454/

相关文章:

html - 如何给网页添加空间?

javascript - 无法控制 z-index 最小的 div

jquery - 为什么这个 Jquery 内容 slider 在 Chrome 和 Safari 中有效,但在 Firefox 中无效?

javascript - 如何将 css 添加到 Jquery 中的 .after 函数

html - 全页宽度边框,居中内容,最好的方法?

html - 如何使::-webkit-scrollbar-thumb 变小?

HTML 电子邮件两列问题

javascript - 选中复选框后如何验证我的表单字段?

javascript - 如果子 <ul> 存在,如何向父 <li> 项添加样式?

javascript - jQuery resize() 函数导致堆栈溢出异常