简体   繁体   English

如何停止移动背景图像位置

[英]how to stop moving background-image position

I've background image and by using small javascript code, it moves from right to left. 我有背景图片,通过使用小的JavaScript代码,它从右向左移动。

HTML code HTML代码

<div id="clouds_image"></div>

Javascript code Javascript代码

var g=0;
var speed=30;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
scroller=setTimeout(function(){rollClouds()},speed);
}
window.addEventListener?
window.addEventListener('load',rollClouds,false):
window.attachEvent('onload',rollClouds);

But i've noticed that, with time my PC CPU memory usage increased ! 但我注意到,随着时间的推移我的PC CPU内存使用量增加了! causing overload on my pc and if i disabled that javascript code, it back to normal. 导致我的电脑过载,如果我禁用了javascript代码,它恢复正常。

My question 我的问题

so i think i need to modify this javascript code that it not keep working forever, i mean, i want to make it to repeat that action only 5 times then stop , maybe i need to define value of g but i'm not good in javascript so any help ~ Thanks. 所以我认为我需要修改这个javascript代码,它不会永远保持工作,我的意思是,我想让它重复该动作只有5次然后停止,也许我需要定义g值,但我不是很好javascript所以任何帮助〜谢谢。

A cleaner solution might be to use jQuery to move the background: 一个更干净的解决方案可能是使用jQuery来移动背景:

function moveClouds() {
    $("#clouds_image").css({left:"-2000px"});
    $("#clouds_image").animate({left:"2000px"},10000);
}

Then you might set an interval to trigger it every x milliseconds. 然后,您可以设置一个间隔,每隔x毫秒触发一次。

setInterval(moveClouds,10000)

JSFiddle is here: http://jsfiddle.net/qXpVX/ JSFiddle在这里: http//jsfiddle.net/qXpVX/

You need to use a variable to count how many times that function was executed, and use setInterval instead of setTimeout: See example 您需要使用变量来计算执行该函数的次数,并使用setInterval而不是setTimeout:请参阅示例

http://jsfiddle.net/EQDjx/206/ (my counter start from 100 and goes down to 0) http://jsfiddle.net/EQDjx/206/ (我的计数器从100开始,下降到0)

for a more nice effect i recomand you to use jquery. 为了更好的效果,我重新使用jquery。 See animate function http://api.jquery.com/animate/ 请参阅动画功能http://api.jquery.com/animate/

var g = 1000;
var speed=300;
var counter = 100;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
if (counter < 1) clearInterval(interval);
}
interval = setInterval(function(){rollClouds()}, speed)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM