在 div 的边界内对图片进行动画处理
Animating a picture within border of div
我有一些代码可以多次在屏幕上移动 image/element。我的想法是,我正在尝试创建一个简单的添加栏,图像在添加栏内移动,该元素充当 bar/the 实际栏的边框。
根据我当前的设置,尽管图像位于 / 内,但在动画期间图像移到了元素之外。
fiddle(可能需要寻找新图片):http://jsfiddle.net/rwowf5j8/3/
<body onload="setInterval(function(){anim(document.getElementById('test'), 'left', 'px', 300, 800, 500)}, 600)">
<div id="Advert">
<img src="JS.png" id="test">
</div>
</body>
<script>
function anim(elem,style,unit,from,to,time) {
if( !elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+unit;
if( step == 1) clearInterval(timer);
},30);
elem.style[style] = from+unit;
}
</script>
</body>
#Advert {
background-color: white;
border-style: solid;
border-width: 2px;
width: 500px;
height: 225px;
left: 300px;
}
#test {
position: absolute;
left: 140px;
}
http://jsfiddle.net/rwowf5j8/5/
添加
#Advert {
position: relative;
/*left: 300px;*/
overflow: hidden;
}
此外,left: 300px 将不起作用,除非您添加 position: relative。
为您的容器提供相对定位并隐藏溢出的元素将解决您的问题:
#Advert {
background-color: white;
border-style: solid;
border-width: 2px;
width: 500px;
height: 225px;
overflow: hidden;
position: relative;
}
因为容器现在是相对的,所以我也删除了 left: 300px
。
我有一些代码可以多次在屏幕上移动 image/element。我的想法是,我正在尝试创建一个简单的添加栏,图像在添加栏内移动,该元素充当 bar/the 实际栏的边框。
根据我当前的设置,尽管图像位于 / 内,但在动画期间图像移到了元素之外。
fiddle(可能需要寻找新图片):http://jsfiddle.net/rwowf5j8/3/
<body onload="setInterval(function(){anim(document.getElementById('test'), 'left', 'px', 300, 800, 500)}, 600)">
<div id="Advert">
<img src="JS.png" id="test">
</div>
</body>
<script>
function anim(elem,style,unit,from,to,time) {
if( !elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+unit;
if( step == 1) clearInterval(timer);
},30);
elem.style[style] = from+unit;
}
</script>
</body>
#Advert {
background-color: white;
border-style: solid;
border-width: 2px;
width: 500px;
height: 225px;
left: 300px;
}
#test {
position: absolute;
left: 140px;
}
http://jsfiddle.net/rwowf5j8/5/
添加
#Advert {
position: relative;
/*left: 300px;*/
overflow: hidden;
}
此外,left: 300px 将不起作用,除非您添加 position: relative。
为您的容器提供相对定位并隐藏溢出的元素将解决您的问题:
#Advert {
background-color: white;
border-style: solid;
border-width: 2px;
width: 500px;
height: 225px;
overflow: hidden;
position: relative;
}
因为容器现在是相对的,所以我也删除了 left: 300px
。