gpt4 book ai didi

javascript - 如何为不同设置的多个元素添加滚动背景效果?

转载 作者:行者123 更新时间:2023-11-30 10:52:23 25 4
gpt4 key购买 nike

在这个演示中 http://www.htmldrive.net/items/demo/527/Animated-background-image-with-jQuery

此代码仅适用于一个背景。我想添加多个具有不同方向和速度的背景。

 var scrollSpeed = 70;
var step = 1;
var current = 0;
var imageWidth = 2247;
var headerWidth = 800;

var restartPosition = -(imageWidth - headerWidth);

function scrollBg(){
current -= step;
if (current == restartPosition){
current = 0;
}

$('#header').css("background-position",current+"px 0");
}

var init = setInterval("scrollBg()", scrollSpeed);

目前它有设置

  $('#header').css("background-position",current+"px 0");

在网站中,我也想在 #footer#content 背景上使用此效果。但速度和方向不同。

有没有更好更优化的jquery方法达到同样的效果?

我们可以使用 CSS 3 而不使用 javascript 获得同样的效果吗?

最佳答案

刚看到 OP 的回答,但还是决定发帖:

我创建了一个 jQuery 插件来执行此操作:

(function($) {
$.fn.scrollingBackground = function(options) {
// settings and defaults.
var settings = options || {};
var speed = settings.speed || 1;
var step = settings.step || 1;
var direction = settings.direction || 'rtl';
var animStep;

// build up a string to pass to animate:
if (direction === 'rtl') {
animStep = "-=" + step + "px";
}
else if (direction === 'ltr') {
animStep = '+=' + step + "px";
}

var element = this;

// perform the animation forever:
var animate = function() {
element.animate({
backgroundPosition: animStep + " 0px"
}, speed, animate);
};
animate();
};
})(jQuery);

用法:

$("#header").scrollingBackground({
speed: 50,
step: 50,
direction: 'ltr'
});

这是非常基本的,并假设您的背景重复是您调用它的元素上的“repeat-x”。这样,就无需经常重置背景位置。

工作示例:http://jsfiddle.net/andrewwhitaker/xmtpr/

关于javascript - 如何为不同设置的多个元素添加滚动背景效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4534669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com