用背景将Div锁定到固定位置

时间:2015-02-19 23:51:51

标签: javascript jquery html css

即使我们调整浏览器大小,我也试图将黄色div元素保持在内部窗口,但我只能用css实现它,所以寻找JavaScript解决方案。

这是我的小提琴:http://jsfiddle.net/jj4fxpmy/6/

当我调整浏览器大小时,问题是黄色方块向上移动。我希望它坚持到房子里。对我来说,保持背景位置正确是非常重要的:

<div class="background"></div>
<div style="position: fixed; background: none repeat scroll 0% 0% gold; top: 50%; z-index: 2147483647; height: 50px; width: 50px; left: 79%;" id="square"></div>

.background{width:100%;height:100%;top:0%;left:0%;position:fixed;
 background:url(http://wallpapers.7savers.com/seasons---summer-wallpapers_1146_1920x1200.jpg) no-repeat; background-color:transparent; background-position:right bottom; background-size:100%;

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

你只需要通过CSS就可以实现这个目的,无需添加js。使用图像标记而不是背景,并在其中添加黄色div。你可以参考下面的代码。

请参阅HTML     

  <img src="http://wallpapers.7savers.com/seasons---summer-wallpapers_1146_1920x1200.jpg" alt="">
  <div>
  <div class="yellow-div" id="square"></div>
  </div>
</div>

参见CSS

.background{
  width:100%;
  height:auto;
  top:0%;
  left:0%;
  position:fixed;
}
.background img{
width:100%;
}

 .yellow-div{
background: none repeat scroll 0 0 gold;
    height: 3.1%;
    position: absolute;
    right: 18.1%;
    top: 68.9%;
    width: 1.6%;
}

您可以参考此http://jsbin.com/pacewepari/2/edit?html,css,output

答案 1 :(得分:0)

如果绝对必须将房屋图像设置为右下方的背景,您可以尝试参考这个问题: jQuery - drag div css background 或者尝试这个插件: https://github.com/kentor/jquery-draggable-background

这是我的疯狂想法:

  1. 使用50x50黄色框创建与房屋图像尺寸相同的透明图像。
  2. 将其设置为背景,并具有与房屋背景相同的样式/定位。
  3. 在引用的溢出问题或Kentor的jquery插件中使用jquery将其连接起来
  4. ......应该这样做!