javascript - 缩放div中的背景图像

标签 javascript jquery html

我知道有一些插件可用于缩放网页的背景图像,但这有点不同。

我正在尝试让 div 按比例调整大小,并且内部的背景图像也按比例调整大小。它适用于水平调整大小。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title></title>
 <style type="text/css" media="screen">

  body {
   background: #000;
   overflow-x: hidden;
   overflow-y: hidden;
  }
  #bg
  {
   z-index: -1;
   position: absolute;
   top:0;
   left:0;
  }

  #wrap
  {
   position: relative;
   margin: 0 auto;
  }
 </style>

</head>
<body>

 <div id="wrap">
  <img src="bg.jpg" id="bg" width="100%" />


  hi
 </div>
 <script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">

 </script>
 <script type="text/javascript" charset="utf-8">

  var minWidth = 400;
  var minHeight = 400;
  var maxWidth = 500;
  var maxHeight = 500;

  function resize() {
   var windowWidth = $(window).width();
   var windowHeight = $(window).height();

   var w = windowWidth < minWidth ? minWidth :
   windowWidth > minWidth && windowWidth < maxWidth ? windowWidth :
   windowWidth > maxWidth ? maxWidth :
   minWidth;

   var h = windowHeight < minHeight ? minHeight :
   windowHeight > minHeight && windowHeight < maxHeight ? windowHeight :
   windowHeight > maxHeight ? maxHeight :
   minHeight;

   $("#wrap").css({
    'width': w + 'px',
    'height': h + 'px'
   });





  }

  $(document).ready(function() {

   resize();
      $(window).resize(function() {
        resize();
      });
  });


 </script>


</body>
</html>

最佳答案

您可以使用普通的 <img> 而不是使用真实背景。使用绝对定位来标记和模拟背景。概念证明:http://jsfiddle.net/yahavbr/vu4Zh/

HTML 代码:

<div id="ImageContainer">
   <img class="background" src="mybackground.gif" border="0" />
    <div class="contents">
        Hello World
    </div>
</div>

CSS:

#ImageContainer { width: 300px; position: relative; }
#ImageContainer .background { width: 100%; position: absolute; left: 0px; top: 0px; z-index: 1; }
#ImageContainer .contents { position: absolute; left: 0px; top: 0px; z-index: 99; }

通过这个,图像将自动缩放到其容器,不涉及脚本。

关于javascript - 缩放div中的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4783075/

相关文章:

javascript - 如何在 three.js 中正确加载 json 模型?

javascript - 如何让我的下拉导航在页面滚动时不会出现错误?

php - ajax获取下拉依赖值

javascript - jquery:如何使用onchange更新输入值?

javascript - 如何在没有 html div(id 或类)的情况下将数据从 Laravel View 传递到 Ajax 或 Javascript 代码 - Laravel 5.3

javascript - 禁用在 IE8 中有效,但在较低版本的 IE 中无效

javascript - 在数据表中定义列类型以进行排序

jquery - scrollTo (jQuery) 在 Firefox 中不起作用

JavaScript:覆盖函数

html - 为什么 IE8 在 HTML 密码字段中显示问号而不是项目符号?