如何仅在具有正文背景的容器div内显示图像?

时间:2018-02-27 16:07:24

标签: jquery html css

我一直在尝试使用图像移动动画的一些基本代码,利用absolute位置属性并在页面加载时更改left上的setInterval值。

以下是HTML代码:

<html>
  <head>
    <title>Moving out of border</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
    <div id='container'>
      <img class='movingimage' src='https://avatars2.githubusercontent.com/u/716412?s=460&v=4'>
    </div>
    <!--<div id='container' style='background: #000000;'>-->
  </body>
</html>

这就是CSS:

body {
  background: url('http://www.gfcf14greendream.com/images/gamesbackground2.png') no-repeat;
  font-size: 0px;
}

#container {
  display: inline-block;
  position: relative;
  z-index: 1;
  width: 500px;
  height: 300px;
  background: #6495ed;
}

.movingimage {
  position: absolute;
  z-index: 2;
  top: 130px;
  left: 8px;
  width: 80px;
  height: 40px;
}

这是Javascript:

$(function() {  
  setInterval(function() {
    var currLeft = $('.movingimage').position().left;
    currLeft += 3;
    if (currLeft < 510) {
      $('.movingimage').css({left: currLeft + 'px'});
    }    
  }, 20);  
});

或者,您可以看到我的代码here

所以基本上,我这样做的页面有一个背景图像,其中具有背景颜色的容器具有向右移动的图像。一旦图像完全越过容器的边界,它就应该停止。

我想要做的只是在容器内部显示图像。这意味着,如果图像的一半越过边界,则只显示留在内部的一半。

我尝试使用另一个容器(注释掉的div)旁边的那个包含图像的容器作为封面,一旦图像超出界限,虽然这样做我想要达到同样的效果没有它的事情。有没有办法实现这个目标?

与往常一样,提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

overflow: hidden添加到CSS文件中的#container选择器,如下所示:

#container {
    overflow: hidden;
}

由于您的img标记是#container的子标记,如果它超出#container的范围,它将被CSS剪切。