如何在背景图像上上下滑动图像以创建扫描效果

How can I slide a image up and down over a background image to create a scanning effect?

本文关键字:图像 创建 扫描 上下 背景      更新时间:2023-09-26

我可以看到一个很好的扫描效果(在GTmetrix上),其中图像在背景图像上上下移动。

他们使用JavaScript来实现这一点,但我想知道这是否可以用CSS来实现,或者如果不能,我如何用JavaScript来实现?

我的代码是:

<style>
  #screenshot {
    margin: 8px auto 0 auto;
    border-radius: 8px;
    border: 2px solid #e4e4e4;
    width: 300px;
    height: 225px;
    background: url("background-box.png") no-repeat center center;
    position: relative;
  }
  #scanner {
    position: absolute;
    top: -7px;
    left: -19px;
  }
</style>
<div id="screenshot">
  <img src="scanner.png" alt="" id="scanner" />
</div>

如果你想用javascript做这件事,这里有一个我做的工作示例。你必须使用jquery来获取scannerdiv。它有无尽的动画,你可以改变速度和高度。速度必须是毫秒(1000ms是1秒)animatescanner(高度、速度);

链接:http://jsfiddle.net/kfg9nutx/1/

Javascript:

x = 0;
xstate=0;
function animatescanner(height,speed){
setInterval(function(){ animateit(height); },speed);
}
function animateit(height){
    if(x==0){xstate=0}
    if(xstate==0){x++}
    if(xstate==1){x--}
    if(x==height){xstate=1}
    $("#scanner").css("top",x);
}
animatescanner(225,5);

不要忘记包含jquery。

使用jQuery animate函数可以很容易地做到这一点:http://api.jquery.com/animate/

<div id="screenshot">
  <img src="scanner.png" alt="" id="scanner" style="position:relative; left:0px;" />
</div>

并在您希望图像移动时调用javascript:

<script>$("#scanner").animate({left:50}, 5000);</script>

也可以使用边距而不是位置设置动画。堆栈溢出的另一个问题。。。使用动画从位置A缓慢移动到位置B